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:
[SecurityPermission(SecurityAction.Demand,
Flags = SecurityPermissionFlag.UnmanagedCode)]
public static Image FastFromFile(string filename)
{
try
{
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 |
BindingFlags.InvokeMethod,
null,
null,
new object[] { loadingImage });
}
catch (SecurityException)
{
return Image.FromFile(filename, true);
}
}
Comments
- Anonymous
April 01, 2004
Out of curiosity, have you noted any significant additional overhead when calling FastFromFile due the run-time stack trawling performed by the full demand?