First off, why use PNG instead of GIF? Probably the most important reason is that GIF supports a maximum of 256 colors. The second reason is Unisys has a lockdown on the rights to LZW compression which the GIF format can, and usually does use. PNG overcomes the color depth hurdle by providing up to 48Bpp (bits per pixel). Just as importantly, the PNG format is patent-free and available for use by anyone.

PNG has other advantages over GIF as well:

So we know PNG offers us plenty of features and flexibility, but how do we use that? It just so happens GDI+ supports PNG, but there are a few extra steps involved in using it.

Let's start by creating a Bitmap and Graphics object, and filling it with red:

Bitmap myBitmap = new Bitmap( 100, 100 );
Graphics myGraphics = Graphics.FromImage( myBitmap );
myGraphics.Clear( Color.Red );

This gives us a simple 100x100 red Bitmap. Now lets focus on saving this as a PNG file. You might think, hey I can just do

myBitmap.Save( "image.png", ImageFormat.Png );

Obviously this is how you save most other image types with GDI. However PNG is a special exception. It requires a seekable stream, such as that offered by System.IO.FileStream. Let's take a look:

FileStream myFileOut = new FileStream( "image.png", FileMode.Create );
myBitmap.Save( myFileOut, ImageFormat.Png );
myFileOut.Close();

As you can see, we merely needed to create a file stream and pass that to the Bitmap Save method.

Stay tuned for part 2 where I discuss how to use those neat features I mentioned in the beginning of the article.

For more information on these topics:

Portable Network Graphic Format

Introduction to GDI+