如何从和向数据库保存和检索图像 [英] How to save and retreive Image from and to database
问题描述
我有一个带有不同Tab控件的Windows窗体与我的数据库连接
i能够存储和重新显示所有值,如名称,年龄,DOB但我有存储pictire和retreiving它的问题。 。
到目前为止存储到数据库工作正常
i可以看到选择图片并加载datagrid视图后我可以看到我的图片,
这里这是我的代码------
I got a windows form with different Tab control connected with my database
i am able to store and reteive all values like name ,age ,DOB but i am having problem with storing pictire and retreiving it..
So far with storing to database work fine
i can see after select a picture and load datagrid view i can see my picture,
Here is my code for doing it------
// foreach (DataRow row in dataset.Tables[1].Rows)
{
row[Name] = textboxName.Text; //Values from my Tabcontrol Text box
row["Dob"] = datetimepickerDob.value;;
//Now for storing image
if (picFoto.Image != null)
{
Bitmap bmp = new Bitmap(picFoto.Image);
System.IO.MemoryStream imgMemoryStream = new System.IO.MemoryStream();
imgMemoryStream.ToArray();
bmp.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imgByteData = imgMemoryStream.GetBuffer();
row["Foto"] = imgByteData;
}
现在在此之后,当我去bach ko我的gridview包含所有表格数据时,我可以在那里看到照片.. .Ok
现在当我想加载这个tabcontrol我想在我的图片框中加载这张照片。
与其他数据类型完全可以,但我遇到了问题加载我的图片
这是我的代码
Now after this when i go bach ko my gridview which contains all table data i can see photo there...Ok
Now when i want to load this tabcontrol i want to load also this photo in my picturebox.
with other data types its perfectly ok but i am having problem on loading my pic
Here is my Code
Applicant aa = new Applicant();
//Apllicant is my class containing all member and properties
//for column items.
foreach (DataGridViewRow dgvr in dataGridView.SelectedRows)
{
DataRowView drv = (DataRowView)dgvr.DataBoundItem;
aa.m_dr = drv.Row;
aa.Name = bb.m_dr["Name"].ToString();
if (aa.m_dr["Foto"] != DBNull.Value)
{
//MemoryStream ms = new MemoryStream();
//Image returnImage = Image.FromStream(ms);
aa.Foto = (Image)bb.m_dr["Foto"];//After this line i got error message cannot convert System.Byte[] to System.Drawing.Image
}
Foto的数据类型是使用sqlce的图像
datatype for Foto is Image using sqlce
推荐答案
尝试使用MemoryStream:
Try to use a MemoryStream:
//aa.Foto = (Image)bb.m_dr["Foto"];
byte[] data = (byte[]) bb.m_dr["Foto"];
MemoryStream ms = new MemoryStream(data);
aa.Foto = Image.FromStream(ms);
这篇关于如何从和向数据库保存和检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!