Once you’ve made images, it’s time to store them. To do this, you must convert the image into a file format. Each file format encodes and compresses differently. Some, like JPEG, use a lossy compression. This means that JPEG will lose details and grow fuzzier. It can never be restored to the original state. Lossless formats encode the image in a way that doesn’t lose information.
The simplest image format is the uncompressed BMP format. This format can be described in a simple table.
|0x0a||4||54 (Location of the pixel array data)|
|0x0e||4||40 (bytes in the header, from this point)|
|0x1c||2||24 (bit depth)|
|0x1e||4||0 (no compression)|
|0x22||4||(Size of the raw bitmap data, including padding)|
|0x26||4||2835 (pixels/meter horizontal)|
|0x2a||4||2835 (pixels/meter vertical)|
|0x2e||4||0 (colors in the palette)|
|0x32||4||0 (all colors are important)|
|Each line is padded to a 4 byte boundary|
|Lines are stored bottom line first, top line last|
As far as image formats go, this is the simplest by far. It takes perhaps a half hour to code and fully test. Notice there’s a header section, which contains pixel width, height and other important information. The data follows the header. There will always be header information followed by pixel data.
The PNG file format is a little more involved. If you want to implement it yourself then you need to read the entire standard. In addition, you will also need RFC1950, RFC1951 and RFC1952. Together these describe the compression method used in PNG. Most programmers reach this stage and just implement a PNG library to load or save. Writing one is pretty straight forward, it just takes a lot of time.
There’s one other feature common in image formats, and that’s segmented data. Consider a large image and transferring that image online. If the connection is slow, then the other side receives part of an image at a time. To make this easier to display, the image format splits the data into chunks. Each chunk is independently compressed, so the computer on the other side can decompress a chunk and add that data to the displayed image. This way an image can be displayed as it arrives. Some image formats take this into account when storing the image. They store a low resolution image first then add progressively more detail with each chunk. The GIF standard is well known for this. It was designed when computers and networking were less developed, so a user could cancel the download if they saw the image wasn’t what they wanted.
Generally accepted image formats are GIF, JPEG and PNG. To compress the images as much as possible, the image formats are complex. While it’s possible to write an image file format library, most programmers use well established image libraries to store and retrieve data. The file format for each image type is freely available, so if you want a challenge then it’s waiting for you.