簡體   English   中英

字節數組到顯示的圖像

[英]byte array to image displayed

嗨,我正在嘗試從數據庫中獲取字節數組,並將其轉換為可用於在.aspx頁中顯示數據庫圖像的內容。 我嚴格使用c#。

這是我的代碼。

SqlCommand picCommand = connection.CreateCommand();
picCommand.CommandText = ("SELECT ItemImage FROM Inventory WHERE ItemName = '" +         DropDownList1.SelectedItem.Text + "';");
connection.Open();

object returnPic; 
returnPic = picCommand.ExecuteScalar();//value that is read as the byte array or intended to be read as byte array.


    connection.Close();


    UTF8Encoding utf8 = new UTF8Encoding();
    //where i intend to convert the 
    byte[] image = utf8.GetBytes(returnPic.ToString()); 


    System.Drawing.Image myImage;

    using (MemoryStream inStream = new MemoryStream())
    {
        inStream.Write(image, 0, image.Length);

        myImage = Bitmap.FromStream(inStream);
    }




    this.ItemImageBox.Equals(myImage);

代碼會編譯並運行,但是到執行myImage = Bitmap.FromStream(instream)行時,我收到此錯誤System.ArgumentException:參數無效。 實際上,我是通過查看各種不同的來源獲得此代碼的,因此也許有人可以告訴我是否做錯了什么。

謝謝你!

你可以嘗試這樣的事情,它應該適合你

public static Image LoadImage(byte[] imageBytes)
{
     Image image = null;
     using (var inStream = new MemoryStream(imageBytes))
     {
        image = Image.FromStream(ms);
     }
     return image;
}

這是一種擴展方法,我必須將字節數組轉換為位圖。在本示例中,我使用將數據保存到Sql Server 2008R2數據庫中

    protected void btnParent1Upload_Click(object sender, EventArgs e)
    {
        ScriptManager.GetCurrent(this).RegisterPostBackControl(this.btnParent1Upload);
        FileUpload FileUpload1 = file_ImageParent1;
        string virtualFolder = "~/UpImages/";
        string physicalFolder = Server.MapPath(virtualFolder);
        FileUpload1.SaveAs(physicalFolder + FileUpload1.FileName);
        lbl_ResultParent1.Text = "Your file " + FileUpload1.FileName + " has been uploaded.";
        Parent1Pic.Visible = true;
        Parent1Pic.ImageUrl = virtualFolder + FileUpload1.FileName;
        byte[] imageBytes = PopulateImageBytes(physicalFolder + FileUpload1.FileName);
        ParentsInfo.Parent1Pic = imageBytes;
        imageBytes = null;
        FileUpload1 = null;
    }

    private static byte[] PopulateImageBytes(string p)
    {
        byte[] imageBytes = File.ReadAllBytes(p);
        return imageBytes;
    }

我將StudentPic定義如下

public byte[] StudentPic { get; set; }

我有以下定義的SQL參數之一

sqlcmd.Parameters.AddWithValue("@Picture", (object)StudentPic ?? noImage);

這應該可以幫助您了解執行此操作的不同方法之一

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM