Friday, January 16, 2009

Image.Save produces Bitmap with an incorrect header

The above two images will be referred to as good (left) and bad (right). They both look alike, but their headers contain a small difference. Most applications do not seem to mind this but some will give an invalid bitmap error when you use the bitmap saved from Visual Studio 2005. To recreate the bug:
Just create a VB.Net program and do the following:
Dim img1 As Bitmap = New Bitmap("c:\good.bmp")
img1.Save("c:\bad.bmp", Imaging.ImageFormat.Bmp)

Not sure if when you download the above two images if you'll get what I was working with, but just use any bitmap images. These are color, I've been able to recreate this issue using grayscale 8bit images at 500 ppi. If you were to open both bitmaps in a binary viewer you will see that that the header of bad.bmp is different. The good has the field "size of the image data" (offset 34) as F4080900, while the bad has the size of the image data as 00000000. I've also seen situations where the good has the field (offset 47) "number of colors in image" as 00 while the bad has it as 01. I am using Visual Studio 2005 SP1 and working with Visual Basic.

My solution was to create a function in C and to call that from the VB program instead of using the native Image.Save. I can't show that solution right now.

Additionally, the following incident seems to allude to a similar problem with the header but their problem looks to be different than ours.

The field header locations and values were found on this website:

No comments: