“無法從帶有索引像素格式的映像建立graphics對象”

來源:互聯網
上載者:User

大家在用 .NET 做圖片浮水印功能的時候, 很可能會遇到 “無法從帶有索引像素格式的映像建立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("圖片路徑")  

原因是因為圖片是索引像素格式的。為了避免此問題的發生,我們在做浮水印之前,可以先判斷原圖片是否是索引像素格式的,如果是,則可以採用將此圖片先clone到一張BMP上的方法來解決: 

 

 1/**//// <summary>
 2/// 會產生graphics異常的PixelFormat
 3/// </summary>
 4private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare,
 5PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
 6PixelFormat.Format8bppIndexed
 7    };
 8
 9/**//// <summary>
10/// 判斷圖片的PixelFormat 是否在 引發異常的 PixelFormat 之中
11/// </summary>
12/// <param name="imgPixelFormat">原圖片的PixelFormat</param>
13/// <returns></returns>
14private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
15{
16    foreach (PixelFormat pf in indexedPixelFormats)
17    {
18        if (pf.Equals(imgPixelFormat)) return true;
19    }
20
21    return false;
22}
23
24//使用
25using (Image img = Image.FromFile("原圖片路徑"))
26{
27    //如果原圖片是索引像素格式之列的,則需要轉換
28    if (IsPixelFormatIndexed(img.PixelFormat))
29    {
30        Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
31        using (Graphics g = Graphics.FromImage(bmp))
32        {
33            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
34            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
35            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
36            g.DrawImage(img, 0, 0);
37        }
38        //下面的浮水印操作,就直接對 bmp 進行了
39        //
40    }
41    else //否則直接操作
42    {
43         //直接對img進行浮水印操作
44    }
45}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.