C and C++ don't have any standard library to work with graphics, GUI or media, diversely from some other programming languages, which support natively such kinds of facilities. Nevertheless, a myriad of open source libraries written in C and C++ does exist, which can be used to manipulate virtually any image or media type and to build GUIs for any kind of device or platform.
However, using third-party libraries makes writing a program that operates on images, for the C/C++ beginner, a little tricky. This is due, in part, to the complexity of the installation and configuration process of these libraries, in part, to the new API which a user must learn before using them.
But, if you are a beginner and all you want is to experiment with images in C or C++, regardless of the image's format, there's an easy shortcut to it.
The Netpbm image formats
In the Netpbm package are implemented various portable image formats, supported by all major platforms. What makes these formats great for beginners, is the fact that they can be used without installing any development library, thus without learning any new API.
In fact, in the Netbpm image formats, data can be represented in Ascii code, which makes creating an image file as easy as writing to a text file. Data can also be written directly in binary mode, using always the standard C/C++ functions, normally used to write text to a common text stream.
The main image types among the Netpbm are three: PBM, PGM and PPM.
The P stands for "portable", while the M stands for "map". The B, the G and P in the middle, stand for "bitmap", "grey" and "pixmap", respectively. Also, there is an alpha and an arbitrary depth format.
The header section of a Netpbm image is very minimalistic and simple. It is made by a magic number, used as a descriptor for the type of data, and some values, defining the size of the image and the maximum number of colours in it.
The header attributes are as follow:
image extension | magic number | image colours |
PBM | P1(ascii) P4(binary) | 2 black/white |
PGM | P2(ascii) P5(binary) | 255 Greys |
PPM | P3(ascii) P6(binary) | 255 RGB |
So, for example, if we wanted to create an image with a width of 7 and with a height of 6 containing only grey pixels, with a value between 0 and 255, we'd write the following header:
P2 7 6 255
Soon after the header, we can start writing the image's data, inserting each pixel's value in the exact order in which it appears on the screen
0 | 0 | 0 | 0 | 0 | 0 | 0 |
0 | 255 | 255 | 255 | 255 | 255 | 0 |
0 | 255 | 128 | 128 | 128 | 255 | 0 |
0 | 255 | 128 | 128 | 128 | 255 | 0 |
0 | 255 | 255 | 255 | 255 | 255 | 0 |
0 | 0 | 0 | 0 | 0 | 0 | 0 |
Now, this is a very small image, but it's big enough to understand how "it" works. The one below is a scaled version:
In the next post, we will see how it's simple to create cool images using C or C++.
No comments:
Post a Comment