1.將Image圖像文件存入到數(shù)據(jù)庫(kù)中 我們知道數(shù)據(jù)庫(kù)里的Image類(lèi)型的數(shù)據(jù)是"二進(jìn)制數(shù)據(jù)",因此必須將圖像文件轉(zhuǎn)換成字節(jié)數(shù)組才能存入數(shù)據(jù)庫(kù)中。
//根據(jù)文件名(完全路徑)
public byte[] SetImageToByteArray(string fileName)
{ FileStream fs = new FileStream(fileName, FileMode.Open);
int streamLength = (int)fs.Length; byte[] image = new byte[streamLength];
fs.Read(image, 0, streamLength);
fs.Close();
return image; }
//另外,在ASP.NET中通過(guò)FileUpload控件得到的圖像文件可以通過(guò)以下方法
public byte[]
SetImageToByteArray(FileUpload FileUpload1)
{ Stream stream = FileUpload1.PostedFile.InputStream;
byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
stream.Read(photo, 0, FileUpload1.PostedFile.ContentLength);
stream.Close();
return photo;
}
2.從SQL Server數(shù)據(jù)庫(kù)讀取Image類(lèi)型的數(shù)據(jù),并轉(zhuǎn)換成bytes[]或Image圖像文件
//要使用SqlDataReader要加載using System.Data.SqlClient命名空間
//將數(shù)據(jù)庫(kù)中的Image類(lèi)型轉(zhuǎn)換成byte[] public byte[] SetImage(SqlDataReader reader)
{ return (byte[])reader["Image"];//Image為數(shù)據(jù)庫(kù)中存放Image類(lèi)型字段 }
//將byte[]轉(zhuǎn)換成Image圖像類(lèi)型 //加載以下命名空間using System.Drawing;/using System.IO;
using System.Data.SqlClient;*/ public Image SetByteToImage(byte[] mybyte)
{ Image image; MemoryStream mymemorystream = new MemoryStream(mybyte,0, mybyte.Length);
image = Image.FromStream(mymemorystream);
return image;
}