轉:http://www.cnblogs.com/jeffwongishandsome/archive/2009/08/27/1554440.html
1、存取圖片
(1)、將圖片文件轉換為二進制並直接存進sql server
//UploadHelper.cs /// <summary> /// 將圖片轉化為長二進制 /// </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> /// 將轉換成二進制碼的圖片保存到數據庫中 /// </summary> public static bool SaveEmployeeImg2Db(Employee model, string path) { try { Byte[] imgBytes = SetImgToByte(path); model.Photo = imgBytes; bool flag=EmployeeService.SaveEmployeePhoto(model); //EmployeeService是公司內部的庫調用,插入或者更新照片,這里不透露細節 return flag; } catch (Exception ex) { throw ex; } }
//將圖片轉換為字節流 FileStream fileStream = new FileStream(path + fileName, FileMode.Open, FileAccess.Read); Byte[] byteData = new Byte[fileStream.Length]; fileStream.Read(byteData, 0, byteData.Length); fileStream.Close(); a.Picture = byteData;//賦值 int result = _accessoryRepository.Update(a);//操作 //ADO.NET
SqlParameter p_Picture = new SqlParameter("@Picture", SqlDbType.Image);
p_Picture.Value = obj.Picture;
(2)、在網頁中上傳圖片
/// <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); //轉成二進制 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)、從數據庫取出照片(返回格式Image)
//UploadHelper.cs /// <summary> /// 將二進制轉化為圖片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); } catch { img = null; } return img; }
上面的這個方法取出來之后,如果在winform下,直接給一個PictureBox的Image屬性賦值就可以了。可是web下沒有這么強大的控件,所以,就有了下面的步驟。
2、直接在網頁中以流的形式顯示圖片
(1)、生成圖片流頁面(ImgHelper .aspx)
這個頁面的設計頁面什么也沒有,類文件如下:
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; using System.IO; /// <summary> /// 圖片輔助類 /// </summary> public partial class ImgHelper : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request["employeeId"])) //需要顯示照片的頁面傳遞的員工id { int employeeId = int.Parse(Request["employeeId"]); Employee model = //EmployeeService.GetEmployeeByCondition(new Employee(employeeId))[0] as Employee; //內部函數 查找一個員工 不透漏細節 try { Byte[] byteImg = model.Photo; Stream stream = new MemoryStream(byteImg); System.Drawing.Bitmap img =(System.Drawing.Bitmap) System.Drawing.Bitmap.FromStream(stream, false); //轉換成Bitmap Response.Buffer = false; Response.ContentType = "image/jpg"; Response.AddHeader("Content-Disposition", "attachment;filename=photo.jpg");//照片名稱叫photo.jpg Response.BinaryWrite(byteImg);//寫入二進制流 Response.End(); } catch { Response.End(); } } } }
(2)、顯示照片的頁面調用ImgHelper .aspx
在頁面加載的時候,給圖片控件賦值如下:
this.imgPhoto.ImageUrl = "/ImgHelper.aspx?employeeId="+tmpEmployee.Id.ToString(); //imgPhoto是圖片控件
/// <summary> /// 為圖片生成縮略圖 /// </summary> /// <param name="phyPath">原圖片的路徑</param> /// <param name="width">縮略圖寬</param> /// <param name="height">縮略圖高</param> /// <returns></returns> public System.Drawing.Image GetThumbnail(System.Drawing.Image image, int width, int height) { Bitmap bmp = new Bitmap(width, height); //從Bitmap創建一個System.Drawing.Graphics System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp); //設置 gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //下面這個也設成高質量 gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; //下面這個設成High gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //把原始圖像繪制成上面所設置寬高的縮小圖 System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, width, height); gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel); return bmp; }