大家在用 .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("圖檔路徑")
這個調用的語句上,通過查詢
MSDN, 我們可以看到如下的提示資訊:
通過上面的錯誤解釋,我們可以看到,原因是因為圖檔是索引像素格式的。為了避免此問題的發生,我們在做水印之前,可以先判斷原圖檔是否是索引像素格式的,如果是,則可以采用将此圖檔先clone到一張BMP上的方法來解決:
/// <summary>/// 會産生graphics異常的PixelFormat/// </summary>private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare,
PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
PixelFormat.Format8bppIndexed
};
/// <summary>/// 判斷圖檔的PixelFormat 是否在 引發異常的 PixelFormat 之中/// </summary>/// <param name="imgPixelFormat">原圖檔的PixelFormat</param>/// <returns></returns>private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
{
foreach (PixelFormat pf in indexedPixelFormats)
{
if (pf.Equals(imgPixelFormat)) return true;
}
return false;
}
//.........使用using (Image img = Image.FromFile("原圖檔路徑"))
//如果原圖檔是索引像素格式之列的,則需要轉換
if (IsPixelFormatIndexed(img.PixelFormat))
Bitmap bmp = new Bitmap(img.Width, img.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(img, 0, 0);
}
//下面的水印操作,就直接對 bmp 進行了
//......
else //否則直接操作
//直接對img進行水印操作
-------------------------------------------------------------------------------------------
以上屬于轉載,友情連結:http://www.cnblogs.com/qixuejia/archive/2010/09/03/1817248.html ,另外之前做測試deno已就緒,有問題或者有需要的可以聯系郵箱 [email protected]