功能需求:
1、把一張圖片(png bmp jpeg bmp gif)轉(zhuǎn)換為byte數(shù)組存放到數(shù)據(jù)庫。
2、把從數(shù)據(jù)庫讀取的byte數(shù)組轉(zhuǎn)換為Image對象,賦值給相應(yīng)的控件顯示。
3、從圖片byte數(shù)組得到對應(yīng)圖片的格式,生成一張圖片保存到磁盤上。
這里的Image是System.Drawing.Image。
以下三個(gè)函數(shù)分別實(shí)現(xiàn)了上述三個(gè)需求:
// Convert Byte[] to Image
private Image ByteToImage(byte[] buffer)
{
MemoryStream ms = new MemoryStream(buffer);
Image image = System.Drawing.Image.FromStream(ms);
return image;
}
// Convert Byte[] to a picture
private string CreateImageFromByte(string fileName, byte[] buffer)
{
string file = fileName; //文件名(不包含擴(kuò)展名)
Image image = ByteToImage(buffer);
ImageFormat format = image.RawFormat;
if (format.Equals(ImageFormat.Jpeg))
{
file += ".jpeg";
}
else if (format.Equals(ImageFormat.Png))
{
file += ".png";
}
else if (format.Equals(ImageFormat.Bmp))
{
file += ".bmp";
}
else if (format.Equals(ImageFormat.Gif))
{
file += ".gif";
}
else if (format.Equals(ImageFormat.Icon))
{
file += ".icon";
}
//文件路徑目錄必須存在,否則先用Directory創(chuàng)建目錄
File.WriteAllBytes(file, buffer);
return file;
}
|
新聞熱點(diǎn)
疑難解答
圖片精選