一、用C#將Image轉換成byte[]並插入資料庫:
1.1 將圖片控制項的Image轉換成流:
複製代碼 代碼如下:private byte[] PicToArray()
{
Bitmap bm = new Bitmap(picBox.Image);
MemoryStream ms = new MemoryStream();
bm.Save(ms, ImageFormat.Jpeg);
return ms.GetBuffer();
}
複製代碼 代碼如下:
//儲存到資料庫
try
{
string sql = "update T_Employee set ImageLogo=@ImageLogo where EmpId=@EmpId";
SqlHelper.ExecuteNonQuery(sql, new SqlParameter("@ImageLogo", imgSourse));
MessageBox.Show("修改已儲存!");// ShowInfo(0);
}
catch (Exception ex)
{
MessageBox.Show("更新失敗!" + ex.Message);
return;
}
1.2將圖片檔案轉換成位元組流並插入資料庫: 複製代碼 代碼如下:class ImageInserter
{
public static int InsertImg(string path)
{
//----------以檔案的方式讀取圖片並轉化成位元組流
FileStream fs = new FileStream(path,FileMode.Open);
byte[] imgSourse = new byte[fs.Length];
fs.Read(imgSourse,0,imgSourse.Length);
fs.Close();
using (SqlConnection conn = new SqlConnection(SqlHelper.connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "update T_Employee set ImageLogo=@ImageLogo";
// cmd.Parameters.Add("@ImageLogo", SqlDbType.Image);
cmd.Parameters.Add(new SqlParameter("@ImageLogo", imgSourse));
return cmd.ExecuteNonQuery();
}
}
}
二、將圖片資料從SQLserver中取出來並顯示到pictureBox控制項上: 複製代碼 代碼如下: byte[] ImageLogoArray = row["ImageLogo"] is DBNull ? null :(byte[])(row["ImageLogo"]);
MemoryStream ms=null;
if (ImageLogoArray!=null)
{
ms = new MemoryStream(ImageLogoArray);
picBox.Image = new Bitmap(ms);
}