在寫下列這一段程式時,發現 System.Drawing.Graphics.FromImage 居然會直接拋出 System.Exception:
public class AddImageInfo : BaseImageOp
{
private Font _drawFont = new Font( "Verdana", 10);
private SolidBrush _drawBrush = new SolidBrush(Color.White);
public AddImageInfo(ImageOp innerOp) : base(innerOp)
{
}
public override Image Execute(Image image)
{
using (Graphics g = Graphics.FromImage(_innerOp.Execute(image)))
{
string info = String.Format( "{0}x{1}", image.Width, image.Height);
g.DrawString( info, _drawFont, _drawBrush, 10, 10);
}
return image;
}
}
用 Reflector 查了 System.Drawing.Graphics.FromImage() 的實作:
public static Graphics FromImage(Image image)
{
if (image == null)
{
throw new ArgumentNullException("image");
}
if ((image.PixelFormat & PixelFormat.Indexed) != PixelFormat.Undefined)
{
throw new Exception(
SR.GetString("GdiplusCannotCreateGraphicsFromIndexedPixelFormat"));
}
IntPtr ptr1 = IntPtr.Zero;
int num1 = SafeNativeMethods.GdipGetImageGraphicsContext(new HandleRef(image, image.nativeImage), out ptr1);
if (num1 != 0)
{
throw SafeNativeMethods.StatusException(num1);
}
return new Graphics(ptr1);
}
這段程式碼的作者好歹也用個 ArgumentException 吧。只好暫時用下列方式避免:
public override Image Execute(Image image)
{
if ((image.PixelFormat & PixelFormat.Indexed) != PixelFormat.Undefined)
{
return image; // do nothing.
}
...
}
因為我不想寫這麼醜的code:
public override Image Execute(Image image)
{
try
{
...
}
catch (Exception ex)
{
// We will ignore ALL EXCEPTIONS (synchronous or asynchronous).
}
return image;
}