【问题标题】:How can i add image in a datatable?如何在数据表中添加图像?
【发布时间】:2013-03-01 02:02:42
【问题描述】:

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

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

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

【问题讨论】:

  • 您需要访问该对象的正确属性才能获取图像。
  • 你有图片对象或图片路径。
  • 你好。您是否设法解决了这个问题?因为我现在就拥有它,但下面的答案都没有帮助。

标签: c# asp.net .net gridview datatable


【解决方案1】:

使用此代码:

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

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

Code Project

【讨论】:

    【解决方案2】:

    试试这个代码:

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

    【讨论】:

    • 第一种方法不起作用。显示 Byte[] 数组而不是图像。
    【解决方案3】:

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

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

    例如

    dr = dt.NewRow();
    dr[column] = "~/images/xx.png";
    
    <asp:TemplateField>
         <ItemTemplate>                    
             <img src='<%#Eval("NameOfColumn")%>' />
         </ItemTemplate>
    </asp:TemplateField>
    

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

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 2016-11-02
      • 2015-12-02
      • 2020-06-23
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多