C# byte數(shù)組與Image相互轉(zhuǎn)換的方法
功能需求:
1、把一張圖片(png bmp jpeg bmp gif)轉(zhuǎn)換為byte數(shù)組存放到數(shù)據(jù)庫(kù)。
2、把從數(shù)據(jù)庫(kù)讀取的byte數(shù)組轉(zhuǎn)換為Image對(duì)象,賦值給相應(yīng)的控件顯示。
3、從圖片byte數(shù)組得到對(duì)應(yīng)圖片的格式,生成一張圖片保存到磁盤(pán)上。
這里的Image是System.Drawing.Image。
以下三個(gè)函數(shù)分別實(shí)現(xiàn)了上述三個(gè)需求:
// Convert Image to Byte[]
private byte[] ImageToByte(Image image)
{
ImageFormat format = image.RawFormat;
using (MemoryStream ms = new MemoryStream())
{
if (format.Equals(ImageFormat.Jpeg))
{
image.Save(ms, ImageFormat.Jpeg);
}
else if (format.Equals(ImageFormat.Png))
{
image.Save(ms, ImageFormat.Png);
}
else if (format.Equals(ImageFormat.Bmp))
{
image.Save(ms, ImageFormat.Bmp);
}
else if (format.Equals(ImageFormat.Gif))
{
image.Save(ms, ImageFormat.Gif);
}
else if (format.Equals(ImageFormat.Icon))
{
image.Save(ms, ImageFormat.Icon);
}
byte[] buffer = new byte[ms.Length];
//Image.Save()會(huì)改變MemoryStream的Position,需要重新Seek到Begin
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, buffer.Length);
return buffer;
}
}
// 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;
}
- C# Stream 和 byte[] 之間的轉(zhuǎn)換
- C# 字符串string和內(nèi)存流MemoryStream及比特?cái)?shù)組byte[]之間相互轉(zhuǎn)換
- C#中Byte[]和String之間轉(zhuǎn)換的方法
- C#實(shí)現(xiàn)Stream與byte[]之間的轉(zhuǎn)換實(shí)例教程
- C#中string與byte[]的轉(zhuǎn)換幫助類(lèi)-.NET教程,C#語(yǔ)言
- C#中兩個(gè)byte如何相加
- C#中圖片.BYTE[]和base64string的轉(zhuǎn)換方法
- C#中Byte轉(zhuǎn)換相關(guān)的函數(shù)
- C#如何從byte[]中直接讀取Structure實(shí)例詳解
相關(guān)文章
c#調(diào)用存儲(chǔ)過(guò)程實(shí)現(xiàn)登錄界面詳解
2013-03-03
詳解C#如何為某個(gè)方法設(shè)定執(zhí)行超時(shí)時(shí)間
這篇文章主要為大家詳細(xì)介紹一下C#如何為某個(gè)方法設(shè)定執(zhí)行超時(shí)時(shí)間,文中的示例代碼簡(jiǎn)潔易懂,具有一定的借鑒價(jià)值,有需要的小伙伴可以學(xué)習(xí)一下2023-10-10
C# WinForm捕獲全局變量異常 SamWang解決方法
本文將介紹C# WinForm捕獲全局變量異常 SamWang解決方法,需要的朋友可以參考2012-11-11
.NET利用C#字節(jié)流動(dòng)態(tài)操作Excel文件
在.NET開(kāi)發(fā)中,通過(guò)字節(jié)流動(dòng)態(tài)操作Excel文件提供了一種高效且靈活的方式處理數(shù)據(jù),本文將演示如何在.NET平臺(tái)使用C#通過(guò)字節(jié)流創(chuàng)建,讀取,編輯及保存Excel文件,需要的可以參考下2024-12-12
給c#添加SetTimeout和SetInterval函數(shù)
Javascript中的SetTimeout和SetInterval函數(shù)很方便,把他們移植到c#中來(lái)。2008-03-03

