الطريقة كالتالي :
أنشئ حقل في Database من نوع Binary اسمه stream
ثم استعمل الكود التالي لحفظ الصورة
كود
OpenFileDialog op=new OpenFileDialog();
op.Filter ="Bitmap Files (*.BMP)|*.bmp |Gif (*.Gif)|*.gif|JPEG (*.JPG*.JPEG;*.JPE;*.JFIF)|*.JPG*.JPEG;*.JPE;*.JFIF|TIFF (*.TIF;*.TIFF)|*.TIF;*.TIFF|ICO (*.ICO)|*.ICO ";
op.ShowDialog();
if(!(op.FileName==""))
{
byte[] content = ReadBitmap2ByteArray(op.FileName);
StoreBlob2DataBase(content);
}
تحويل الصورة لبايت
protected static byte[] ReadBitmap2ByteArray(string fileName)
{
using(Bitmap image = new Bitmap(fileName))
{
MemoryStream stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
return stream.ToArray();
}
}
تخزين الصورة في قاعدة البيانات
protected static void StoreBlob2DataBase(byte[] content)
{
SqlConnection con =new SqlConnection (DbConnectioncls.ConnectionString());
DbConnectioncls.Open_Connection(con);
//con.Open();
try
{
SqlCommand insert = new SqlCommand(
"update Company_Info set [stream] = (@image) where company_id=1",con);
SqlParameter imageParameter =
insert.Parameters.Add("@image", System.Data.SqlDbType.Binary);
imageParameter.Value = content;
imageParameter.Size = content.Length;
insert.ExecuteNonQuery();
}
finally
{
DbConnectioncls.Close_Connection(con);
}
}
والكود التالي لقرائتها من قاعدة البيانات
كود
string sqlstr;
sqlstr="select * from Company_Info_Vw where Company_ID = '1'";
SqlCommand DBCmd = new SqlCommand (sqlstr, con );
SqlDataReader dr =null;
dr = DBCmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
if (dr["stream"] != DBNull.Value )
{
byte[] content = (byte[])dr["stream"];
MemoryStream stream = new MemoryStream(content);
Bitmap image = new Bitmap(stream);
pictureBox1.Image = image;
}
else
pictureBox1.Image = null;
إن شاء الله أكون قد وصلت المعلومة