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