Image as output!

Hi,

I'm writing a program that should produce an image as the output...
Can anyone help?
FreeImage and ImageMagick are the most popular free image manipulation libraries.
There are also BMP and TGA files, two of the simplest file formats in existance.

For example, a TGA:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <fstream>
#include <string>
using namespace std;

typedef unsigned char byte;
typedef struct
  {
  byte red, green, blue;
  }
  RGB_t;

// It is presumed that the image is stored in memory as 
//   RGB_t data[ height ][ width ]
// where lines are top to bottom and columns are left to right
// (the same way you view the image on the display)

// The routine makes all the appropriate adjustments to match the TGA format specification.

bool write_truecolor_tga( const string& filename, RGB_t* data, unsigned width, unsigned height )
  {
  ofstream tgafile( filename.c_str(), ios::binary );
  if (!tgafile) return false;

  // The image header
  byte header[ 18 ] = { 0 };
  header[  2 ] = 1;  // truecolor
  header[ 12 ] =  width        & 0xFF;
  header[ 13 ] = (width  >> 8) & 0xFF;
  header[ 14 ] =  height       & 0xFF;
  header[ 15 ] = (height >> 8) & 0xFF;
  header[ 16 ] = 24;  // bits per pixel

  tgafile.write( (const char*)header, 18 );

  // The image data is stored bottom-to-top, left-to-right
  for (int y = height -1; y >= 0; y--)
  for (int x = 0; x < width; x++)
    {
    tgafile.put( (char)data[ (y * width) + x ].blue  );
    tgafile.put( (char)data[ (y * width) + x ].green );
    tgafile.put( (char)data[ (y * width) + x ].red   );
    }

  // The file footer. This part is totally optional.
  static const char footer[ 26 ] =
    "\0\0\0\0"  // no extension area
    "\0\0\0\0"  // no developer directory
    "TRUEVISION-XFILE"  // yep, this is a TGA file
    ".";
  tgafile.write( footer, 26 );

  tgafile.close();
  return true;
  }

Hope this helps.

[edit] BTW, I just typed this in... I didn't test it, so I may have typoed or otherwise made a really stoopid mistake somewhere. I don't think I did.... but just so you know. :-)
Last edited on
Oh, how could I have forgotten the simpler formats?

RAW is even simpler, but it won't work if you need to create images of different sizes or bit depths.
Last edited on
Just so he knows your code you forgot using namespace std; Just in case he gets confused why it won't build.
Fixed. :-)


It depends on what you are doing. If all you want is something you can load in xv or paint, then a simple dump is fine. Otherwise I wholly agree with helios and also recommend using an imaging library.
Last edited on
Wooo - your code worked fine by the way - i didn't realize you could do this so I gave it a little test. So cheers for the info heh
Topic archived. No new replies allowed.