C program to write an image in PGM format
PGM stands for Portable Gray Map. Saving a 2D array in C as images in PNG, JPG or other formats would need a lot of effort to encode the data in the specified format before writing to a file.
However, Netpbm format offers a simple solution with easy portability.
A Netpbm format is any graphics format used and defined by the Netpbm project. The portable pixmap format (PPM), the portable graymap format (PGM) and the portable bitmap format (PBM) are image file formats designed to be easily exchanged between platforms.
Netpbm is an open-source package of graphics programs and a programming library. It is used mainly in the Unix world, where one can find it included in all major open-source operating system distributions, but also works on macOS, and others. It also works under Microsoft Windows.
Each file starts with a two-byte magic number (in ASCII) that identifies the type of file it is (PBM, PGM, and PPM) and its encoding (ASCII or binary). The magic number is a capital P followed by a single-digit number.
The ASCII formats allow for human readability and easy transfer to other platforms; the binary formats are more efficient in file size but may have native byte-order issues.
In the binary formats, PBM uses 1 bit per pixel, PGM uses 8 bits per pixel, and PPM uses 24 bits per pixel: 8 for red, 8 for green, 8 for blue.
The PGM and PPM formats (both ASCII and binary versions) have an additional parameter for the maximum value (numbers of grey between black and white) after the X and Y dimensions and before the actual pixel data. Black is 0 and max value is white. There is a newline character at the end of each line.
How to write PGM files?
The File format is as follows:
1. Magic Number “P2”
2. Whitespace (blanks, TABs, CRs, LFs).
3. A width, formatted as ASCII characters in decimal.
5. A height, again in ASCII decimal.
7. The maximum gray value, again in ASCII decimal.
9. width X height gray values, each in ASCII decimal, between 0 and the specified maximum value, separated by whitespace, in raster format, from top to bottom.
Steps to compile and execute the code in Ubuntu
- First, save the file as “write_pgm_img.c“.
- For compiling the C file, open terminal (Ctrl+Alt+T) and enter the following line of code
gcc -o write_pgm_img write_pgm_img.c
- For executing the code enter
- The PGM image will be saved as pgmimg.pgm.
The Image will look like this:
Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.