繁体   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