System.Drawing.Image Performance Update

Update: I've been informed that using the method below can have significant consequences in the future. Using private reflection isn't a good idea because the private methods can change in the future and this code WILL BREAK. Be forewarned.

Well, thanks to Justin Rogers you can have lightning fast loading of Jpeg images w/o having to wait for a Service Pack or get a hotfix from Microsoft as I recently blogged about.

I tested his code and found no difference in speed between the method I was using and his method. Since using his method will work on .NET Framework 1.1 it's the preferred solution. You still need permission to run Unmanaged Code.

One way to handle the need for Unmanaged permission is to add this attribute to the function and then add a try/catch and use the regular method in the catch:

Flags = SecurityPermissionFlag.UnmanagedCode)]
public static Image FastFromFile(string filename)
filename = Path.GetFullPath(filename);
IntPtr loadingImage = IntPtr.Zero;

if (GdipLoadImageFromFile(filename, out loadingImage) != 0 )
throw new Exception("GDI+ threw a status error code.");

return (Bitmap) imageType.InvokeMember("FromGDIplus",
BindingFlags.NonPublic |
BindingFlags.Static |
new object[] { loadingImage });
catch (SecurityException)
return Image.FromFile(filename, true);

Comments (1)
  1. Kevin Westhead says:

    Out of curiosity, have you noted any significant additional overhead when calling FastFromFile due the run-time stack trawling performed by the full demand?

Comments are closed.

Skip to main content