大家在用 .NET 做圖片浮水印功能的時候, 如果原圖片是GIF格式, 很可能會遇到
“無法從帶有索引像素格式的映像建立graphics對象”這個錯誤,對應的英文錯誤提示是“A Graphics object cannot be
created from an image that has an indexed pixel format"
這個exception是出現在 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage("圖片路徑")
這個調用的語句上,通過查詢 MSDN, 我們可以看到如下的提示資訊:
為了避免此問題的發生,可以採用將此GIF圖片先clone到一張BMP上的方法來解決:
using (Image sourceImage = Image.FromFile("原圖片路徑"))
{
////判斷原圖片是否是GIF圖片
if (sourceImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
{
Bitmap bmp = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
////提高圖片品質
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(sourceImage, 0, 0);
}
////現在的 bmp就代替了原來的gif圖片,下面的操做,就全部針對這個 bmp 進行就是了
}
}
經過上面的轉換, 就可以避免因圖片的索引資訊而引發異常了。
原文:http://www.zu14.cn/2008/12/19/net_gif_index_error/