C# 数据表中的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/905419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:29:35  来源:igfitidea点击:

Image in datatable

c#imagedatatable

提问by Shamim

I read image by using OpenFileDialog. Sample code is below:

我使用 OpenFileDialog 读取图像。示例代码如下:

openFileDialog1.ShowDialog();
if (openFileDialog1.FileName != null)
   if (picBoardImage.Image != null)
{
    picBoardImage.Image.Dispose();
}
picBoardImage.Image = Image.FromFile(openFileDialog1.FileName);

I want to store this image in datatable. How can I do that?

我想将此图像存储在数据表中。我怎样才能做到这一点?

回答by Kirtan

You can do it like this -

你可以这样做 -

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.

Then, add a new row to this table and set the value of the MyImagecolumn.

然后,向该表添加新行并设置该MyImage列的值。

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

EDIT: You can take a look at thisCodeProject article for help on converting an image to a byte array.

编辑:您可以查看CodeProject 文章以获取有关将图像转换为字节数组的帮助。

回答by John

I was actually trying to accomplish this as well. My solution actually is not that involved.

我实际上也在努力实现这一目标。我的解决方案实际上并不涉及。

Drawing.Bitmap img = new Drawing.Bitmap("Path to image"); //Replace string with your OpenFileDialog path.

DataColumn column = new DataColumn("ImageColumn");
column.DataType = System.Type.GetType("System.Drawing.Bitmap");

//Code to add data to a cell:
DataRow row = new DataRow();
row("ImageColumn") = img;

For me this worked like a charm.

对我来说,这就像一种魅力。