How can i add image in a datatable?

不羁岁月 提交于 2019-12-12 08:59:12

问题


How can i add image in a datatable ? I tried the following code,

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

But it showing text System.Web.UI.WebControls.Image in gridview instead of image.


回答1:


try this code:

        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);

where imageToByteArray is

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

so Idea is that don't try to store the Image directly, rather convert it to byte [] and then store it, so that, later you can refetch it and use it or assign it to a picture box like this:

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

where byteArrayToImage is:

    public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }



回答2:


Use this code:

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.

Add new row to table:

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

Check out the following Code project link(Image to byte[]):

Code Project




回答3:


If the purpose is to display an image within a GridView, then personally I wouldn't store the actual image within a DataTable, only the image path. Storing the Image would only bloat the DataTable unnecessarily. Obviously this is only if your image is stored on the FileSystem and not in a DataBase.

To display the image within the GridView use a TemplateField

e.g.

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

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

This would also work well when you are storing the Image path in a Database rather than storing the raw image.



来源:https://stackoverflow.com/questions/15380187/how-can-i-add-image-in-a-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!