[C#] 圖片存檔(在 GDI+ 中發生泛型錯誤)
Introduction
今天在實做圖片存檔的時候 image.Save() 出現 GDI+ 中發生泛型錯誤 ,如圖
這邊紀錄一下,利用專案來模擬當時的情況。
Example
sample1 存檔時出現錯誤(如上圖)
using System.IO;
namespace TestImageSave {
public partial class Form1 : Form {
byte[] _SourceImage;
public Form1() {
InitializeComponent();
}
private void btnReadImage_Click(object sender, EventArgs e) {
Image image = Image.FromFile("test.jpeg");
this.pictureBox1.Image = image;
//將 Image 轉換 Byte 陣列
_SourceImage = this.ImageToBuffer(image);
}
private void btnSaveImage_Click(object sender, EventArgs e) {
//模擬接到 Byte 陣列值 ,轉換為 Image 物件
Image image = this.BufferToImage(_SourceImage);
//將圖片存檔
image.Save("test2.jpeg");
}
private byte[] ImageToBuffer(Image image) {
byte[] buffer = null;
using (Bitmap oBitmap = new Bitmap(image)) {
using (MemoryStream MS = new MemoryStream()) {
oBitmap.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
MS.Position = 0;
buffer = new byte[MS.Length];
MS.Read(buffer, 0, Convert.ToInt32(MS.Length));
MS.Flush();
}
}
return buffer;
}
private Image BufferToImage(byte[] Buffer) {
byte[] data = null;
Image oImage = null;
MemoryStream oMemoryStream = null;
Bitmap oBitmap = null;
//建立副本
data = (byte[])Buffer.Clone();
try {
oMemoryStream = new MemoryStream(data);
//設定資料流位置
oMemoryStream.Position = 0;
oImage = System.Drawing.Image.FromStream(oMemoryStream);
//建立副本
//oBitmap = new Bitmap(oImage);
}
catch {
throw;
}
finally {
oMemoryStream.Close();
oMemoryStream.Dispose();
oMemoryStream = null;
}
return oImage;
//return oBitmap;
}
}
}
觀察檔案資料是否有真正存取?
sample2
上網搜尋,發現當 Image 物件的來源為串流的時候,當串流關閉時,
資料來源也就遺失,所以,當圖片要儲存成檔案時,就會出現錯誤。
將程式修改如下
private Image BufferToImage(byte[] Buffer) {
byte[] data = null;
Image oImage = null;
MemoryStream oMemoryStream = null;
Bitmap oBitmap = null;
//建立副本
data = (byte[])Buffer.Clone();
try {
oMemoryStream = new MemoryStream(data);
//設定資料流位置
oMemoryStream.Position = 0;
oImage = System.Drawing.Image.FromStream(oMemoryStream);
//建立副本
oBitmap = new Bitmap(oImage);
}
catch {
throw;
}
finally {
oMemoryStream.Close();
oMemoryStream.Dispose();
oMemoryStream = null;
}
//return oImage;
return oBitmap;
}
觀察檔案資料是否有真正存取?
程式碼下載 TestImageSave.rar
Refrence
備註
修改 [C#] Image 與 byte[] 互轉 - .NET 隨筆- 點部落 程式碼
三小俠 小弟獻醜,歡迎指教