asp.net(c#)實現(xiàn)從sqlserver存取二進制圖片的代碼
2024-07-10 12:41:45
供稿:網(wǎng)友
下面說說主要實現(xiàn)思路:
1、存取圖片
(1)、將圖片文件轉(zhuǎn)換為二進制并直接存進sql server
代碼如下:
//UploadHelper.cs
/// <summary>
/// 將圖片轉(zhuǎn)化為長二進制
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static Byte[] SetImgToByte(string imgPath)
{
FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
Byte[] byteData = new Byte[file.Length];
file.Read(byteData, 0, byteData.Length);
file.Close();
return byteData;
}
/// <summary>
/// 將轉(zhuǎn)換成二進制碼的圖片保存到數(shù)據(jù)庫中
/// </summary>
public static bool SaveEmployeeImg2Db(Employee model, string path)
{
try
{
Byte[] imgBytes = SetImgToByte(path);
model.Photo = imgBytes;
bool flag=EmployeeService.SaveEmployeePhoto(model); //EmployeeService是公司內(nèi)部的庫調(diào)用,插入或者更新照片,這里不透露細節(jié)
return flag;
}
catch (Exception ex)
{
throw ex;
}
}
(2)、在網(wǎng)頁中上傳圖片
代碼如下:
/// <summary>
/// 上傳圖片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
string serverPath = Server.MapPath("~/images/");
if (this.fuPhoto.HasFile) //fuPhoto是fileupload控件
{
string fileName = this.fuPhoto.PostedFile.FileName;
FileInfo fi = new FileInfo(fileName);
string mimeType = this.fuPhoto.PostedFile.ContentType.ToLower();
if (mimeType.IndexOf("image") < 0)
{
//("上傳的照片格式不對");
}
else if(fi.Length > 2* 1024 * 1024)
{
//圖片大于2M,重新處理
}
else
{
string saveFilePath = serverPath + DateTime.Now.ToString("yyyyMMddHHmmss") + fileName;
try
{
//先存圖片到服務器
this.fuPhoto.PostedFile.SaveAs(saveFilePath);
//轉(zhuǎn)成二進制
Employee model = new Employee(int.Parse(id)); //id是EmployeeId,這里是模擬字段
bool flag = UploadHelper.SaveEmployeeImg2Db(model, saveFilePath);
}
catch
{
//("照片上傳失敗");
}
finally
{
//最后刪掉該圖片
if (System.IO.File.Exists(saveFilePath))
{
System.IO.File.Delete(saveFilePath);
}
}
}
}
else
{
//("全選擇要上傳的照片");
}
}
(3)、從數(shù)據(jù)庫取出照片(返回格式Image)
代碼如下:
//UploadHelper.cs
/// <summary>
/// 將二進制轉(zhuǎn)化為圖片Image
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static System.Drawing.Image GetImgFromByte(Employee model)
{
System.Drawing.Image img = null;
try
{
Stream stream = new MemoryStream(model.Photo);
img = System.Drawing.Image.FromStream(stream,false);