字节数组显示图像

时间:2012-11-14 18:13:58

标签: c# image

您好我正在尝试从数据库中获取一个字节数组并将其转换为我可以用来在我的.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:参数无效。我实际上从查看各种不同的来源获得此代码,所以也许这里的人可以告诉我我是否做错了。

提前致谢!

2 个答案:

答案 0 :(得分:1)

你可以尝试这样的东西,它应该适合你

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

答案 1 :(得分:0)

这是一个扩展方法,我必须将字节数组转换为位图 在这个例子中,我使用的是将数据保存到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 Params定义如下

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

这可以帮助您了解执行此操作的不同方法之一