Although the class of Portable Any Map (PNM) format images -- which includes ASCII and Binary versions of Portable Bit Map (PBM), Portable Grey Map (PGM) and Portable Pixel Map (PPM) images -- represents the "lowest common denominator" of image formats, they are relatively uncommon in modern Windows environments. They also tend to be poorly supported on the free graphics programs for Windows, such as Paint and Paint.NET. Furthermore, I was not (in an admittedly short search) able to find a suitable C# class library for working with these formats programmatically.
Fortunately, the formats are quite simple, so it was relatively easy to build a
PixelMap class to encapsulate these images and expose a couple of
System.Drawing.Bitmap properties (
GreyMap) that can be used easily by other classes. Also, the simple Windows application that I created to test the
PixelMap class rapidly evolved into a fairly competent viewer and converter that can save the current image as a BMP, JPG, TIFF, GIF, or PNG file.
Using the code
To use the
PixelMap class you should:
- Copy the PixelMap.cs file into your own project.
- Change the namespace in the PixelMap.cs file to the name of your project namespace.
- Compile. The
PixelMap class should now be available in your project.
The PixelMapViewer application demonstrates the usage of the
class. It also provides a handy viewing and converting application in its own right.
Points of interest
- There are ASCII and Binary versions of each of the PBM, PGM, and PPM formats. The binary versions are much, much smaller and faster than the ASCII versions. They ought to be used unless there is a compelling reason to make the image file "human readable." Personally, I prefer to "read" my images by "looking at the pictures." This
PixelMap class does not support the binary PBM format (Magic Number P4) at this time.
- Since PBM, PGM, and PPM are UNIX-centric formats, their pixel order is BGR, rather than the RGB order that Windows programmers would tend to expect.
- The "stride" of the image (normally calculated as stride = Image.Width * BytesPerPixel) should be a multiple of 4. If this is not the case, then in many programs the output images will become corrupted as they are processed. However, this is not a problem with the
PixelMap class since it has been designed to work correctly with "off-size" images. However, it does have to use much less efficient (i.e. slow) algorithms relative to the normal direct-memory algorithms that it uses for well-sized images.
25 May, 2007 - Version 188.8.131.52 uploaded to CodeProject