程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C#操作圖片讀取和存儲SQLserver實現代碼

C#操作圖片讀取和存儲SQLserver實現代碼

編輯:C#基礎知識
一、用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);
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved