如何在datatable中添加图像?我尝试了下面的代码,
Image img = new Image();
img.ImageUrl = "~/images/xx.png";
dr = dt.NewRow();
dr[column] = imgdw;
但它在网格视图中显示的是文本System.Web.UI.WebControls.Image
而不是图像。
发布于 2013-03-13 16:35:41
尝试以下代码:
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-13 16:31:58
使用以下代码:
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);
查看以下代码项目链接(指向byte[]的图像):
发布于 2013-03-13 17:07:53
如果其目的是在GridView中显示图像,那么就我个人而言,我不会在DataTable中存储实际的图像,只会存储图像路径。存储图像只会不必要地膨胀DataTable。显然,只有当您的图像存储在FileSystem上而不是DataBase中时,才会出现这种情况。
要在GridView中显示图像,请使用TemplateField
例如:
dr = dt.NewRow();
dr[column] = "~/images/xx.png";
<asp:TemplateField>
<ItemTemplate>
<img src='<%#Eval("NameOfColumn")%>' />
</ItemTemplate>
</asp:TemplateField>
当您在数据库中存储图像路径而不是存储原始图像时,这也可以很好地工作。
https://stackoverflow.com/questions/15380187
复制相似问题