## Recommended Posts

Deliverance    387
Hi, hello again! I have a little problem: I'm trying to save an image in TGA format, here are the functions I'm using:
bool CImage::WriteTGA(char *fileName, int offset)
{
CLogger logger("log.txt");

FILE* Output = fopen(fileName, "wb");

if ( !Output )
{
logger.Message("Error - <WriteTGA>: Cannot write to file %s", fileName);
}

fseek(Output, offset, SEEK_SET);

unsigned char *newData = new unsigned char[width * height * components];
memcpy(newData, pixelData, width * height * components);

// RGB -> BGR
int i;
for ( i = 0; i < width * height; i++)
{
unsigned char temp = newData[i * components + 0];
newData[i * components + 0] = pixelData[i * components + 2];
newData[i * components + 2] = temp;
}

fwrite(newData, width * height * components, 1, Output);

fclose(Output);

delete[] newData;
newData = NULL;

return true;
}

void CImage::SetPixel(int i, int j, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
pixelData[i*width*components + j*components + 0] = r;
pixelData[i*width*components + j*components + 1] = g;
pixelData[i*width*components + j*components + 2] = b;
if ( components == 4 )
pixelData[i*width*components + j*components + 3] = a;
}

tColor4ub CImage::GetPixel(int i, int j)
{
tColor4ub color;
color.r = pixelData[i*width*components + j*components + 0];
color.g = pixelData[i*width*components + j*components + 1];
color.b = pixelData[i*width*components + j*components + 2];
if ( components == 4 )
color.a = pixelData[i*width*components + j*components + 3];

return color;
}

void CImage::CreateEmpty(int width, int height, int components, unsigned char *pixelData)
{
this->width = width;
this->height = height;
this->components = components;

this->pixelData = new unsigned char[width * height * components];
memset(this->pixelData, 0, width * height * components);
if (pixelData)
memcpy(this->pixelData, pixelData, width * height * components);
}


Okay I'm trying to create now, using the functions above an image that will have the top row all white. Instead of that I get an image that has the bottom wor all whitr, why? here is the code that implements this
CImage img;
img.CreateEmpty(64, 64, 3, NULL);
int collon;
for ( collon = 0; collon < 64; ++collon )
img.SetPixel( 0, collon, 255, 255, 255, 255);
img.WriteTGA("test.tga", 0);
img.Free();


and here is the output: (The last line is white :) )

##### Share on other sites
RobTheBloke    2553
because the coord's (x,0) are at the bottom of the image. try filling coords (x,63).....

If the height value is negative, then the image would go the other way (and your code would do as you expect). The only problem with that, is that most people don't support negative widths & heights. So basically, just remember that 0,0 is the bottom left....

##### Share on other sites
Mastaba    761
The last byte of the header normally sets the origin of the image, be it top left, top right, bottom left or bottom right. See this.