1.GDI+ 中發生一般性錯誤。(從資料庫讀取圖片,沒有修改過就寫回資料庫,而引發的)
參考:http://www.cnblogs.com/wudingfeng/archive/2008/07/24/1250564.html
byte[] pic =null; // 儲存的圖片
if (PictureBox1.Image !=null)
{
// 解決"GDI+ 中發生一般性錯誤。"的關鍵
// -----------------------------------------------------------------------------------
Image img = PictureBox1.Image; // 讀取PictureBox的圖片
// 如果檔案格式為空白就設定為Bmp類型
System.Drawing.Imaging.ImageFormat rawFormat =null;
rawFormat = (img.RawFormat ==null) ? System.Drawing.Imaging.ImageFormat.Bmp : img.RawFormat;
Bitmap bmp1 =new Bitmap(img); // 建立一個bitmap類型的bmp變數來讀取檔案。
Bitmap bmp2 =new Bitmap(img.Width, img.Height); // 建立第二個bitmap類型的bmp2變數
Graphics draw = Graphics.FromImage((Image)bmp2);
draw.DrawImage((Image)bmp1, 0, 0);
PictureBox1.Image = (Image)bmp2;
draw.Dispose();
bmp1.Dispose();
//bmp2.Dispose(); // 暫時不能釋放
// -----------------------------------------------------------------------------------
System.IO.MemoryStream imgMS =new System.IO.MemoryStream();
PictureBox1.Image.Save(imgMS, rawFormat);
byte[] imgByte = imgMS.ToArray();
if (imgMS.Length >64*1024)
{
PictureBox1.Image =null; // 清除圖片
if (imgMS !=null) { imgMS.Dispose(); } // 釋放資源
System.Windows.Forms.MessageBox.Show("請選擇容量小於等於64KB的圖片!", "警告",
System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
imgMS.Read(imgByte, 0, Convert.ToInt32(imgMS.Length));
pic = imgByte;
imgMS.Close();
if (imgMS !=null) { imgMS.Dispose(); } // 釋放資源
}
/************** 省略預存程序 **************/
mysqlDA.UpdateCommand.Parameters.AddWithValue("@Photo", pic);
2.無法從帶有索引像素格式的映像建立 Graphics 對象。
參考:http://hi.baidu.com/1987raymond/blog/item/0d2e86a151d969834710649b.html
(浮水印的例子參考:http://dong.hongjun888.blog.163.com/blog/static/2081208420098172655812/)
依照上面代碼[1.GDI+ 中發生一般性錯誤。(從資料庫讀取圖片,沒有修改過就寫回資料庫,而引發的)]
只要在new Bitmap(img.Width, img.Height,像素格式);中去除像素格式就可以了(本人暫時只遇到這種情況,和找到類似的解決方案)
Bitmap bmp2 =new Bitmap(img.Width, img.Height); // 建立第二個bitmap類型的bmp2變數