C# byte數(shù)組與Image相互轉換的方法
功能需求:
1、把一張圖片(png bmp jpeg bmp gif)轉換為byte數(shù)組存放到數(shù)據(jù)庫。
2、把從數(shù)據(jù)庫讀取的byte數(shù)組轉換為Image對象,賦值給相應的控件顯示。
3、從圖片byte數(shù)組得到對應圖片的格式,生成一張圖片保存到磁盤上。
這里的Image是System.Drawing.Image。
以下三個函數(shù)分別實現(xiàn)了上述三個需求:
// 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()會改變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; //文件名(不包含擴展名)
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;
}
相關文章
基于WPF實現(xiàn)帶蒙版的MessageBox消息提示框
這篇文章主要介紹了如何利用WPF實現(xiàn)帶蒙版的MessageBox消息提示框,文中的示例代碼講解詳細,對我們學習或工作有一定幫助,需要的可以參考一下2022-08-08c# winform讀取xml文件創(chuàng)建菜單的代碼
動態(tài)創(chuàng)建菜單使得程序靈活性大大增加,本文根據(jù)讀取xml文件中的配置菜單項來動態(tài)創(chuàng)建菜單,代碼如下2013-09-09C#使用Consul集群進行服務注冊與發(fā)現(xiàn)
這篇文章主要介紹了C#使用Consul集群進行服務注冊與發(fā)現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12C#后端接收form-data,創(chuàng)建實體類教程
這篇文章主要介紹了C#后端接收form-data,創(chuàng)建實體類教程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06