如何在dataGridView中显示图像? [英] How to display images in dataGridView?

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

问题描述

说明.
它应该在数据库中存储 *.ico *.jpg *.png 等图像的路径.
数据库类型:

Description.
It is supposed to store paths to images like *.ico, *.jpg, *.png in the database.
Database types:

  • SQLlite;
  • SQLServer;
  • MySQL;

我正在使用 DataTable dt 来模拟 SELECT 查询的结果.

I am using DataTable dt to simulate the result of a SELECT query.

问题.

  1. 如何在dataGridView中显示图像?
  2. 在数据库中存储图像的最常见做法是什么?存储为路径还是使用其他选项更好?
  3. 代码中是否有任何错误?

我正在运行该应用程序.
结果:错误.
错误:
DataGridView中的异常:
System.FormatException:无效的强制转换"System.String"至"System.Drawing.Image".

I am running the application.
Result: error.
Error:
Exception in DataGridView:
System.FormatException: Invalid cast "System.String" to "System.Drawing.Image".

图片1

代码

public partial class Form1 : Form
{
    DataTable dt = new DataTable();
    string pathProject = AppDomain.CurrentDomain.BaseDirectory;

    public Form1()
    {
        InitializeComponent();

        dgv.CellFormatting += Dgv_CellFormatting;
    }

    private void Dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (dgv.Columns[e.ColumnIndex].Name == "IcoPath")
        {
            string fullpath = pathProject + e.Value.ToString();

            // e.Value = Bitmap.FromFile(fullpath);

            Image p_ImageIn = new Bitmap(fullpath);
            ImageConverter imgConverter = new ImageConverter();
            e.Value = (byte[])imgConverter.ConvertTo(p_ImageIn, typeof(Byte[]));
            e.FormattingApplied = true;
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("IcoPath", typeof(string));
        dt.Columns.Add("JpgPath", typeof(string));
        dt.Columns.Add("PngPath", typeof(string));


        // dt.Rows.Add("Name_1", @"Resources\Picture\ico\ico_1.ico");
        // dt.Rows.Add("Name_2", @"Resources\Picture\ico\ico_2.ico");
        // dt.Rows.Add("Name_3", @"Resources\Picture\ico\ico_3.ico");

        // dt.Rows.Add("Name_1", @"Resources\Picture\jpg\Jpg_1.jpg");
        // dt.Rows.Add("Name_2", @"Resources\Picture\jpg\Jpg_2.jpg");
        // dt.Rows.Add("Name_3", @"Resources\Picture\jpg\Jpg_3.jpg");

        // dt.Rows.Add("Name_1", @"\Resources\Picture\png\Png_1.png");
        // dt.Rows.Add("Name_2", @"\Resources\Picture\png\Png_2.png");
        // dt.Rows.Add("Name_3", @"\Resources\Picture\png\Png_3.png");

        dt.Rows.Add("Name_1", @"Resources\Picture\ico\ico_1.ico", @"Resources\Picture\jpg\Jpg_1.jpg", @"\Resources\Picture\png\Png_1.png");
        dt.Rows.Add("Name_2", @"Resources\Picture\ico\ico_2.ico", @"Resources\Picture\jpg\Jpg_2.jpg", @"\Resources\Picture\png\Png_2.png");
        dt.Rows.Add("Name_3", @"Resources\Picture\ico\ico_3.ico", @"Resources\Picture\jpg\Jpg_3.jpg", @"\Resources\Picture\png\Png_3.png");

        DataGridViewImageColumn icoColumn = new DataGridViewImageColumn();
        //icoColumn.HeaderText = "Image_Header";
        icoColumn.Name = "IcoPath_Name";
        icoColumn.DataPropertyName = "IcoPath";
        //// dgv.Columns.Insert(3, imageColumn);
        dgv.Columns.Add(icoColumn);

        DataGridViewImageColumn jpgColumn = new DataGridViewImageColumn();
        //icoColumn.HeaderText = "Image_Header";
        jpgColumn.Name = "JpgPath_Name";
        jpgColumn.DataPropertyName = "JpgPath";
        //// dgv.Columns.Insert(3, imageColumn);
        dgv.Columns.Add(jpgColumn);


        DataGridViewImageColumn pngColumn = new DataGridViewImageColumn();
        //icoColumn.HeaderText = "Image_Header";
        pngColumn.Name = "PngPath_Name";
        pngColumn.DataPropertyName = "PngPath";
        //// dgv.Columns.Insert(3, imageColumn);
        dgv.Columns.Add(pngColumn);


        dgv.DataSource = dt;
    }
}

图片2

为该问题创建解决方案时,请不要将图像视为嵌入在项目中".
应用逻辑:

When creating a solution for this issue, please do not consider images as "embedded in the project".
Application logic:

  • 连接到数据库;
  • 执行请求;
  • 查询结果: DataTable dt ;
  • DataTable dt 包含图像的路径;
  • connect to the database;
  • execute the request;
  • query result: DataTable dt;
  • DataTable dt contains paths to images;

推荐答案

基本上,由于图像不是来自数据库,而是嵌入在项目中(如解决方案资源管理器图片所示),因此您的代码将必须使用这些嵌入式资源构建"此 DataTable .

Basically, since the images are NOT coming from a DB but are embedded in the project as shown from the solution explorer picture, your code is going to have to "build" this DataTable using those embedded resources.

您要尝试执行的操作是将图片添加"到网格列".您要将图像添加到 DataTable ROWS.然后,将不必要在网格中添加"网格图像"列.网格将知道如何显示 DataTable 中的图像,因为它们是实际"图像.

Is what it appears you are trying to do is "add" the pictures to the grids "column." You want to add the images to the DataTable ROWS. Then, it will be unnecessary to "add" the "grid image" column to the grid. The grid will know how to display the images from the DataTable since they are "actual" images.

下面是一个只有一个图像列的小示例,但是使用相同的策略添加其他列并不难.另外,正如您当前的图片所示,我正在获取作为资源嵌入到项目中的图像.除了图像文件名之外,您还需要使用项目名称更改"ProjectName"文本.

Below is a small example with only one image column, however it should not be difficult to add the other columns using the same strategy. Also, I am getting the images that are embedded as a resource in the project as your current picture shows. You will need to change the text that says "ProjectName" with the name of your project in addition to the image file names.

  DataTable dt = new DataTable();
  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("JpgPath", typeof(Image));

  Assembly myAssembly = Assembly.GetExecutingAssembly();
  Stream myStream = myAssembly.GetManifestResourceStream("ProjectName.Resources.Picture.jpg.image1.jpg");
  Image jpg1 = new Bitmap(myStream);
  myStream = myAssembly.GetManifestResourceStream("ProjectName.Resources.Picture.jpg.image2.jpg");
  Image jpg2 = new Bitmap(myStream);
  myStream = myAssembly.GetManifestResourceStream("ProjectName.Resources.Picture.jpg.image3.jpg");
  Image jpg3 = new Bitmap(myStream);

  dt.Rows.Add("Name1", jpg1);
  dt.Rows.Add("Name2", jpg2);
  dt.Rows.Add("Name3", jpg3);

  dgv.DataSource = dt;

根据OP问题进行编辑.

Edit from OP question.

下面的示例显示了两种方法.第一种是从数据库中获取数据的模拟,该数据库中没有图像,但有图像的字符串路径.

The example below shows two methods. The first is a simulation of getting the data from the DB where the images are not there but the string paths to the images are.

一旦从数据库中获得了 DataTable ,我们就需要将这些图像添加"到现有 DataTable 中的每一行中.显然,我们需要将新的图像"列添加"到从数据库获得的现有 DataTable 中.然后循环浏览每一行,然后根据该行中的路径将图像添加到图像列中.

Once we have the DataTable from the DB, we need to "add" those images to each row in the existing DataTable. Obviously, we need to "add" the new "Image" column to the existing DataTable we got from the DB. Then loop through each row and add the image to the image column based on the path in that row.

private void Form1_Load(object sender, EventArgs e) {
  DataTable DBTable = GetTableFromDB();
  AddImageColumnToDT(DBTable);
  dgv.DataSource = DBTable;
}


private DataTable GetTableFromDB() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("ImagePath", typeof(string));
  dt.Rows.Add("Name1", "PathTo_Image1");
  dt.Rows.Add("Name2", "PathTo_Image2");
  dt.Rows.Add("Name3", "PathTo_Image3");
  return dt;
}

private void AddImageColumnToDT(DataTable dt) {
  dt.Columns.Add("Image", typeof(Image));
  string curPath;
  Image curImage;
  foreach (DataRow row in dt.Rows) {
    curPath = row["ImagePath"].ToString();
    curImage = Image.FromFile(curPath);
    row["Image"] = curImage;
  }
}

EDIT ***,如果DB返回空",则返回***. byte [] 数组列,而不是 Image 类型.

EDIT*** if the DB returns a "empty" byte[] array column instead of an Image type.

private DataTable GetTableFromDB2() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("ImagePath", typeof(string));
  dt.Columns.Add("Image", typeof(byte[]));
  dt.Rows.Add("Name1", "PathTo_Image1");
  dt.Rows.Add("Name2", "PathTo_Image2");
  dt.Rows.Add("Name3", "PathTo_Image3");
  return dt;
}

private void AddImageColumnToDT2(DataTable dt) {
  //dt.Columns.Add("Image", typeof(byte[]));
  string curPath;
  Image curImage;
  byte[] curByteArray;
  foreach (DataRow row in dt.Rows) {
    curPath = row["ImagePath"].ToString();
    curImage = Image.FromFile(curPath);
    curByteArray = imageToByteArray(curImage);
    row["Image"] = curByteArray;
  }
}

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

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

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