我如何在数据表中添加图像? [英] How can i add image in a datatable?

查看:88
本文介绍了我如何在数据表中添加图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

但它显示文本 System.Web.UI.WebControls.Image

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

推荐答案

试试这段代码:

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

所以想法是不要试图直接存储图像,而是转换它到byte []然后存储它,这样,以后你可以重新获取它并使用它或者将它赋值给像这样的图片框:

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

其中 byteArrayToImage 是:

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

这篇关于我如何在数据表中添加图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆