無法從帶有索引像素格式的映像建立graphics對象|A Graphics object cannot be created from an image that has an indexed

來源:互聯網
上載者:User

大家在用 .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/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.