The Linux Page

Quickly saving an image to disk without extra library

Often, when I work with some form of graphics, I do not have a handy library to save the image buffer I'm working with in a file on disk. In most cases, when I want to do that, I make use of the Targa format. This is very easy to save since the header is very simple (18 bytes) and the data can be saved verbatim. Plus, many tools, such as the Gimp, can read the result at once.

Here is my C code to do so. It will work in C++ also. It should be easy to tweak for other languages such as C#.

{
  unsigned char hdr[18]; // the targa file header
  FILE *f;

  memset(hdr, 0, sizeof(hdr)); // reset header by default
  hdr[2] = 2; // ARGB image (note that it is saved in little endian, so it's really BGRA)
  hdr[12] = (unisnged char) width;
  hdr[13] = (unsigned char) (width >> 8);
  hdr[14] = (unisnged char) height;
  hdr[15] = (unsigned char) (height >> 8);
  hdr[16] = depth * 8; // bit depth, 24 if you have RGB only images, 32 otherwise
  hdr[17]  = 32; // options: here we save the top-left corner first
  f = fopen("output.tga", "w");
  fwrite(hdr, sizeof(hdr), 1, f);
  fwrite(image_data, width * height * depth, 1, f);
  fclose(f);
}

That's very easy, isn't it? Now you have an image on disk that you can manipulate with your favorite software.

Note that the depth parameter should be 3 or 4. If you deal with an RGB image (no alpha at all) then 3 is correct. Otherwise, you are likely to be using RGBX or RGBA, then use 4 for the depth.

Obviously, the width, height and depth parameters can all be hard coded. That will depend on your situation.

The image_data is the buffer of RGB[A/X] components. The position of the alpha matters, the other components can be in any order since tools such as the Gimp can be used to swap them back to the right position. That means you don't need to reallocate another buffer just to save the data to disk.

Of course, if your alpha channel is not the 3rd component, then you have a problem. Although in many cases (where I only need a rough idea of what the image looks like) I just shift the data on the fly. In other wods, I use fwrite(image_data + 1, ...); for example. That way, the alpha gets in place. You may then need to write another byte at the end or at the start to make sure you get it right.

Finally, some people will write a few more bytes after the image buffer to clearly indicate that there are no developer information there, It is not required, though.

AttachmentSize
tga_specs.pdf62.01 KB