.net二進制圖片存儲與讀取的常見方法

.NET二進制圖片存儲與讀取的常見方法有如下幾種:html

.NET二進制圖片存儲:以二進制的形式存儲圖片時,要把數據庫中的字段設置爲Image數據類型(SQL Server),存儲的數據是Byte[].數據庫

1.參數是圖片路徑:返回Byte[]類型: app

  1. publicbyte[] GetPictureData(string imagepath)
  2. {
  3. /**/////根據圖片文件的路徑使用文件流打開,並保存爲byte[]
  4. FileStream fs = new FileStream(imagepath, FileMode.Open);//能夠是其餘重載方法
  5. byte[] byData = newbyte[fs.Length];
  6. fs.Read(byData, 0, byData.Length);
  7. fs.Close();
  8. return byData;
  9. }

2.參數類型是Image對象,返回Byte[]類型: asp.net

  1. publicbyte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
  2. {
  3. //將Image轉換成流數據,並保存爲byte[]
  4. MemoryStream mstream = new MemoryStream();
  5. imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
  6. byte[] byData = new Byte[mstream.Length];
  7. mstream.Position = 0;
  8. mstream.Read(byData, 0, byData.Length);
  9. mstream.Close();
  10. return byData;
  11. }

好了,這樣經過上面的方法就能夠把圖片轉換成Byte[]對象,而後就把這個對象保存到數據庫中去就實現了把圖片的二進制格式保存到數據庫中去了。下面我就談談如何把數據庫中的圖片讀取出來,實際上這是一個相反的過程。spa

.NET二進制圖片讀取:把相應的字段轉換成Byte[]即:Byte[] bt=(Byte[])XXXX.net

1.參數是Byte[]類型,返回值是Image對象: excel

  1. public System.Drawing.Image ReturnPhoto(byte[] streamByte)
  2. {
  3. System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
  4. System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
  5. return img;
  6. }

2.參數是Byte[] 類型,沒有返回值,這是針對asp.net中把圖片從輸出到網頁上(Response.BinaryWrite)orm

  1. publicvoid WritePhoto(byte[] streamByte)
  2. {
  3. // Response.ContentType 的默認值爲默認值爲「text/html」
  4. Response.ContentType = "image/GIF";
  5. //圖片輸出的類型有: image/GIF image/JPEG
  6. Response.BinaryWrite(streamByte);
  7. }

補充:htm

針對Response.ContentType的值,除了針對圖片的類型外,還有其餘的類型:對象

  1. Response.ContentType = "application/msword";
  2. Response.ContentType = "application/x-shockwave-flash";
  3. Response.ContentType = "application/vnd.ms-excel";

另外能夠針對不一樣的格式,用不一樣的輸出類型以適合不一樣的類型:  

  1. switch (dataread("document_type"))
  2. {
  3. case"doc":
  4. Response.ContentType = "application/msword";
  5. case"swf":
  6. Response.ContentType = "application/x-shockwave-flash";
  7. case"xls":
  8. Response.ContentType = "application/vnd.ms-excel";
  9. case"gif":
  10. Response.ContentType = "image/gif";
  11. case"Jpg":
  12. Response.ContentType = "image/jpeg";
  13. }

以上就介紹了.NET二進制圖片存儲和讀取的常見方法。

相關文章
相關標籤/搜索