简体   繁体   English

如何在datagridview中保存图像流

[英]how to save stream of image in datagridview

NOTE: this is windows app, sql server as database, ado.net. 注意:这是Windows应用程序,SQL Server作为数据库,ado.net。

i insert images in datagridview temporarily then loop through them and save each row in database. 我将图像临时插入datagridview中,然后遍历它们并将每一行保存在数据库中。 在此处输入图片说明 i know how to insert stream from picturebox like this 我知道如何从这样的图片框插入流

    MemoryStream stream = new MemoryStream();
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
SqlCommand cmda = new SqlCommand("INSERT INTO KeyWord (ItemName, DateEntry,image, imageindex) VALUES (N'" + listBoxI.ToString() + "', GETDATE(), @image, 1)", cn);
cmda.Parameters.AddWithValue("@Pic", pic);
try
{
    cn.Open();
    cmda.ExecuteNonQuery();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    cn.Close();
}

i want to replace pictureBox1 with dataGridView1.Rows[x].Cells[1].Value 我想用dataGridView1.Rows[x].Cells[1].Value替换pictureBox1

my question is how to save images from datagridview? 我的问题是如何从datagridview保存图像?

You can go like this: 您可以像这样去:

Image myImg = (dataGridView1.Rows[x].Cells[1].Value as Image);
myImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

Or in one line without the usage of a variable: 或在一行中不使用变量:

(dataGridView1.Rows[x].Cells[1].Value as Image).Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

You know that the value of DataGridViewImageColumn is Image hence the conversion is safe. 您知道DataGridViewImageColumn值为Image因此转换是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM