Simple tga writer not working correctly.

Hi. I did write code to write a simple tga file format file.

Unfortunately, it does not seem to work as expected. The resulting image is always black, not matter the color values I write on the file. Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <fstream>

using namespace std;

main () {
   int a = 1024;
   int b = 768;
   int c = 24;
   ofstream ofs ("x.tga", ios::binary);
         ofs.put (0), ofs.put (0), ofs.put (2), ofs.put (0), ofs.put (0), ofs.put (0);
         ofs.put (0), ofs.put (0), ofs.put (0), ofs.put (0), ofs.put (0), ofs.put (0);
         ofs.put (a), ofs.put (a >> 8), ofs.put (b), ofs.put (b >> 8);
         ofs.put (c),   ofs.put (0);   
   for (int i=0; i<a; i++)
      for (int j=0; j<b; j++)
         ofs.put (1),          ofs.put (0),          ofs.put (0);         
   ofs.close ();
don't do this to yourself.
set up a tga header struct and use a compiler flag to force the alignment to 0 so that its wysiwyg alignment. Then fill it in and do a ofs.write() of the whole struct, then do an ofs.write of a vector of pixels for the image data. If your machine is the wrong byte order, correct for that on the multi-byte fields.

But to debug it:
open your image editor and create a new tga of the same dimensions that you want with the same format you want (uncompressed 24bit probably) and save it. Open that in a hex editor and look at the header, and compare it to the file that you are writing, and your error should pop right out as "oh, byte 8 was wrong" kind of thing.

Last edited on
You are writing near black pixels.
Try 255, 0, 0 !!!

Also, you are writing the pixels in the wrong order. The outer loop should be for the height and the inner one for the width.

And TGA is a strange format to use these days. If you don't specifically need to use it and are just looking for a simple image format, try netpbm:
https://en.wikipedia.org/wiki/Netpbm
https://netpbm.sourceforge.net/doc/ppm.html

Last edited on
You might consider finding an already existing 3rd party library and using that so you aren't recreating a flat wheel.

https://duckduckgo.com/?t=ffab&q=c%2B%2B+tga+library&ia=web

Finding a library that needs to be compiled from source would be beneficial if you want to understand the ins and out of the format.

https://github.com/tjohnman/Simple-Targa-Library
Topic archived. No new replies allowed.