Monday, June 18, 2007

Next time I work with windows metafile formats and they turn out black bitmaps...

Next time I work with windows metafile formats I should remember that whenever I save the metafile to a bitmap I should clear the black color.

I got a request from a client that i need to show and resize bitmap images (jpeg, gif, tiff, png and bmp) along with .wmf files in a PictureBox, resize the images and embed them into reports.

Bitmaps were not a problem, but resizing and saving metafiles would replace the white areas with black color...

This issue had been addressed in the following forums:
Forum at MSDN

Forum at VelocityReviews

My short term solution:

// load bitmap from file
// sFile is the file name
FileInfo instance = new FileInfo(sFile);
if ((instance.Extension == ".wmf") || (instance.Extension == ".WMF"))
{

System.Drawing.Imaging.Metafile mf = (Metafile)Image.FromFile(sFile, true);

mf.Save(instance.Name+"_temp.bmp", ImageFormat.Bmp);

Image i = Image.FromFile(instance.Name + "_temp.bmp", true);

bmp = new Bitmap(i);
bmp.MakeTransparent(Color.Black);
}

The example above uses file streams but it works as well with memory streams :-p, yes, I'm not going around leaving a bunch of temporary files on the hard drive without doing clean up...

Labels: