5

如何在数据表中添加图像?我尝试了以下代码,

Image img = new Image();
img.ImageUrl = "~/images/xx.png";
dr = dt.NewRow();
dr[column] = imgdw;

但它System.Web.UI.WebControls.Image在 gridview 中显示文本而不是图像。

4

3 回答 3

7

试试这个代码:

        DataTable dt = new DataTable();
        dt.Columns.Add("col1", typeof(byte[]));
        Image img = Image.FromFile(@"physical path to the file");
        DataRow dr = dt.NewRow();
        dr["col1"] = imageToByteArray(img);
        dt.Rows.Add(dr);

imageToByteArray在哪里

    public byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        return ms.ToArray();
    }

所以想法是不要尝试直接存储Image,而是将其转换为byte []然后存储它,以便稍后您可以重新获取它并使用它或将它分配给这样的图片框:

 pictureBox1.Image = byteArrayToImage((byte[])dt.Rows[0]["col1"]);

哪里byteArrayToImage是:

    public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
于 2013-03-13T08:35:40.673 回答
2

使用此代码:

DataTable table = new DataTable("ImageTable"); //Create a new DataTable instance.

DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";

table.Columns.Add(column); //Add the column to the table.

向表中添加新行:

DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);

查看以下代码项目链接(图像到字节 []):

代码项目

于 2013-03-13T08:31:57.770 回答
2

如果目的是在 GridView 中显示图像,那么我个人不会将实际图像存储在 DataTable 中,只存储图像路径。存储图像只会使 DataTable 不必要地膨胀。显然,这仅适用于您的图像存储在文件系统而不是数据库中的情况。

要在 GridView 中显示图像,请使用TemplateField

例如

dr = dt.NewRow();
dr[column] = "~/images/xx.png";

<asp:TemplateField>
     <ItemTemplate>                    
         <img src='<%#Eval("NameOfColumn")%>' />
     </ItemTemplate>
</asp:TemplateField>

当您将图像路径存储在数据库中而不是存储原始图像时,这也可以很好地工作。

于 2013-03-13T09:07:52.977 回答