I ended up using the FreeImageAPI DLL, with a C# wrapper. I try to avoid 3rd party libraries but I don't think there is any other choice. It seems a pretty standard and well used library.
In my case I have an System.Drawing.Image
object 'image'
that was dynamically created - which I want to save to the HttpContext output stream as a compressed image. Note that Image
does not have the needed GetHbitmap()
method, but Bitmap
does.
// convert image to a 'FreeImageAPI' image
var fiBitmap = FreeImageAPI.FreeImageBitmap.FromHbitmap((image as Bitmap).GetHbitmap());
fiBitmap.ConvertColorDepth(FreeImageAPI.FREE_IMAGE_COLOR_DEPTH.FICD_08_BPP);
// see http://stackoverflow.com/questions/582766
MemoryStream ms = new MemoryStream();
fiBitmap.Save(ms, FreeImageAPI.FREE_IMAGE_FORMAT.FIF_PNG, FreeImageAPI.FREE_IMAGE_SAVE_FLAGS.PNG_Z_BEST_COMPRESSION);
context.HttpContext.Response.OutputStream.Write(ms.ToArray(), 0, (int)ms.Length);
My 24kb bitmap is now only 9kb :-)
Tip: Be sure to have both 'FreeImageNET' AND 'FreeImage' dlls available in your bin when you run it. At the current time the C# sample projects contain a reference to 'Library.DLL' which doesn't seem to exist in their zip file. Using FreeImageNET.dll
and FreeImage.dll
works though. You'll get an annoying file not found error if you don't realize that FreeImageNet
!= FreeImage
!