Working With Bitmaps in the .NET Compact Framework

On my latest project I found a need to use Bitmap images in my .NET Compact Framework application. Using Visual Studio 2005 (Beta 2) and the Windows Mobile 5 SDK the application is currently stable on an HP iPAQ running WM5. There are a few things that annoy me about developing on this platform, though, because the Compact Framework 2.0 is still buggy and the API is not well documented nor easy to find on the MSDN site.

I wanted to create a data file that could contain metadata and images so that I didn’t have a mess of extra files hanging around on the PDA. Using XML I want to tag profiles so that meaningful and easy to read data along with an embedded picture can be saved. For understanding purposes the meaningful data would be an email address and the image would be a bitmap. Saving is easy and can be done using the following code:

[code lang=”java”]
public byte[] GetByteArrayFromBitmap(Bitmap TheBMP)
{
// First, create a memory a stream where
// the passed bitmap will be stored
MemoryStream BitmapMS = new MemoryStream();

// Now save the bitmap into the stream
TheBMP.Save(BitmapMS, Imaging.ImageFormat.Bmp);

// Create a byte array that is the same size as the
// memory stream that houses the recently saved bitmap
byte[] BMPArray = new byte[BitmapMS.Length];

// Store the contents of the memory
// stream into byte array
BMPArray = BitmapMS.ToArray();

// Finally, return the byte array
return BMPArray;
}
[/code]

In the above code I transform the bitmap into a byte array (byte[]) using the MemoryStream class. The length of the byte array is stored to the XML file and then the entire byte array is written. Again, this is the easy part. The reverse — turning the byte array into a bitmap image — is not necessarily difficult but it took a while to find.

[code lang=”java”]
public Bitmap GetBitmapFromByteArray(byte[] BMPArray)
{
// First, create a memory a stream where the
// passed byte array will be stored
MemoryStream BitmapMS = new MemoryStream();

// Write the byte array to the memory stream
BitmapMS.Write(BMPArray, 0, BMPArray.Length);

// Create a new bitmap object from the memory stream
Bitmap TheBitmap = new Bitmap(BitmapMS);

// Finally, return the bitmap
return TheBitmap;
}
[/code]

This entry was posted in Software. Bookmark the permalink.

One Response to Working With Bitmaps in the .NET Compact Framework

Leave a Reply

Your email address will not be published. Required fields are marked *