This class supports reading the PNM image format into
System.Drawing.Image and writing it back to PNM format. It makes it possible to inter convert different image file formats including PNM.
PNM is a portable bitmap format used in legacy software. The use of PNM file format is more common in LINUX / UNIX Platform. PNM file format consists of three different file formats namely PBM, PGM and PPM. (Corrections suggested by Andrew Kirillov, thank you.)
- PBM [Portable Bit Map - Binary]
- PGM [Portable Grey Map - GreyScale]
- PPM [Portable Pixel Map - Color]
Each of these file formats, except PBM can be written in ASCII or Binary Encoding. The encoding is determined at reading time against the Identifier each PNM file contains called "Magic Number". This is always the first token of the PNM file.
- "P1" [PBM - ASCII Encoding]
- "P2" [PGM - ASCII Encoding]
- "P3" [PPM - ASCII Encoding]
- "P4" [PBM - Binary Encoding] (not yet implemented)
- "P5" [PGM - Binary Encoding]
- "P6" [PPM - Binary Encoding]
The next two tokens in the PNM header define width and height of the image. The fourth token is the maximum value of the pixel which is present only in the case of PGM and PPM. PBM does not contain this token. Moreover, the header can contain comments beginning with '
Read more about these image formats from the links provided in the Reference section.
The original definitions of PGM and PNM do not describe 16-bit pixel formats. It has, however been used in many practical situations where accuracy/depth of color information matters. This library does not currently support the 16-bit extensions, perhaps an avenue for you to contribute. Read more about it here.
Using the Code
The parameterless constructor of
System.Drawing.Image is marked internal and
System.Drawing.Bitmap is marked as a sealed class, therefore I could not inherit them into my class and hence could not follow true object oriented design.
The code is primarily a class library, a class named PNM contains two overloaded functions to provide its functionality. Since the functions are
static, you do not have to create an object of the said class.
Here is a sample use of the class:
System.Drawing.Image im = ShaniSoft.Drawing.PNM.ReadPNM(FileName);
Both functions may throw
IOException like a normal class would.
Points of Interest
PNM format is very plain in terms of complexity. It contains image subtype, width, height and max value of a pixel in ASCII format. The pixel data is then appended at the end in either binary format or ASCII format (nothing a
BinaryWriter couldn't handle).
- Version 1, conversion from C to C# [PGM Only]
- Version 2, complete PNM Support [PBM, PGM, PPM]
- Corrections made to article regarding PNM format description