I observe sometimes a strange behavior when writing an image-buffer from memory (containing RGBA-pixel-data loaded from a tga-file) to a file back as tga.
The image-buffer is loaded from a TGA-file with an algorithm stolen and adapted from this thread:
Loading a tga/bmp file in C++/OpenGL
The writing-method I have stolen and adapted from this address:
http://www.paulbourke.net/dataformats/tga/
Here is a minimal, compilable example, where tileA.tga is correctly saved back to disc as tileA_new.tga, but the TileB_new.tga is broken (graphic looks strange with false pixels)! Why is TileB_new.tga broken?
The two source tga-files are different, but they can be viewed correctly in gimp and irfanview and I double-checked the load-algorithm. It works, because when I render the image-buffers of both loaded tiles (With OpenGL) to the screen they are appearing correct! But writing the raw-buffers to disc behaves differently, why? I compared the header of the source tga-files in a hex-editor, but they are equal. Also the written tga-files have equal headers. What I can see is, that the size of tileB.tga is 5 times larger than tileA.tga, but that seems to be correct, cause gimp/irfanview are showing them correct. Maybe you can see the mistake I made here?
//A small visual-studio-project inclusive the both tga-files is downloadable here https://www.file-upload.net/download-13208817/StackOverflowTGA.zip.html
Minimal example:
#include <vector>
#include <fstream>
//special-sausage for microsoft
#ifdef _MSC_VER
#pragma warning(disable:4996)
#endif
//=========================================
// Code for loading a TGA-file
//=========================================
typedef union PixelInfo
{
std::uint32_t Colour;
struct
{
std::uint8_t R, G, B, A;
};
} *PPixelInfo;
class Tga
{
private:
std::vector<std::uint8_t> Pixels;
bool ImageCompressed;
std::uint32_t width, height, size, BitsPerPixel;
public:
Tga(const char* FilePath);
std::vector<std::uint8_t> GetPixels() { return this->Pixels; }
std::uint32_t GetWidth() const { return this->width; }
std::uint32_t GetHeight() const { return this->height; }
std::uint32_t GetBitsPerPixel() const { return this->BitsPerPixel; }
bool HasAlphaChannel() { return BitsPerPixel == 32; }
};
Tga::Tga(const char* FilePath)
{
std::fstream hFile(FilePath, std::ios::in | std::ios::binary);
if (!hFile.is_open()) { throw std::invalid_argument("File Not Found."); }
std::uint8_t Header[18] = { 0 };
std::vector<std::uint8_t> ImageData;
static std::uint8_t DeCompressed[12] = { 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
static std::uint8_t IsCompressed[12] = { 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
hFile.read(reinterpret_cast<char*>(&Header), sizeof(Header));
if (!std::memcmp(DeCompressed, &Header, sizeof(DeCompressed)))
{
BitsPerPixel = Header[16];
width = Header[13] * 256 + Header[12];
height = Header[15] * 256 + Header[14];
size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
if ((BitsPerPixel != 24) && (BitsPerPixel != 32))
{
hFile.close();
throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit Image.");
}
ImageData.resize(size);
ImageCompressed = false;
hFile.read(reinterpret_cast<char*>(ImageData.data()), size);
}
else if (!std::memcmp(IsCompressed, &Header, sizeof(IsCompressed)))
{
BitsPerPixel = Header[16];
width = Header[13] * 256 + Header[12];
height = Header[15] * 256 + Header[14];
size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
if ((BitsPerPixel != 24) && (BitsPerPixel != 32))
{
hFile.close();
throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit Image.");
}
PixelInfo Pixel = { 0 };
int CurrentByte = 0;
std::size_t CurrentPixel = 0;
ImageCompressed = true;
std::uint8_t ChunkHeader = { 0 };
int BytesPerPixel = (BitsPerPixel / 8);
ImageData.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * sizeof(PixelInfo));
do
{
hFile.read(reinterpret_cast<char*>(&ChunkHeader), sizeof(ChunkHeader));
if (ChunkHeader < 128)
{
++ChunkHeader;
for (int I = 0; I < ChunkHeader; ++I, ++CurrentPixel)
{
hFile.read(reinterpret_cast<char*>(&Pixel), BytesPerPixel);
ImageData[CurrentByte++] = Pixel.B;
ImageData[CurrentByte++] = Pixel.G;
ImageData[CurrentByte++] = Pixel.R;
if (BitsPerPixel > 24) ImageData[CurrentByte++] = Pixel.A;
}
}
else
{
ChunkHeader -= 127;
hFile.read(reinterpret_cast<char*>(&Pixel), BytesPerPixel);
for (int I = 0; I < ChunkHeader; ++I, ++CurrentPixel)
{
ImageData[CurrentByte++] = Pixel.B;
ImageData[CurrentByte++] = Pixel.G;
ImageData[CurrentByte++] = Pixel.R;
if (BitsPerPixel > 24) ImageData[CurrentByte++] = Pixel.A;
}
}
} while (CurrentPixel < (static_cast<size_t>(width) * static_cast<size_t>(height)));
}
else
{
hFile.close();
throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit TGA File.");
}
hFile.close();
this->Pixels = ImageData;
}
//=========================================
// code for writing a TGA-file
//=========================================
void writeTGA(const std::string &refFile, Tga &refTGA)
{
unsigned short width = static_cast<unsigned short>(refTGA.GetWidth());
unsigned short height = static_cast<unsigned short>(refTGA.GetWidth());
unsigned char bitsPerPixel = static_cast<unsigned char>(refTGA.GetBitsPerPixel());
unsigned char bitsAlphaChannel = (bitsPerPixel == 32 ? 8 : 0);
FILE * fptr = fopen(refFile.c_str(), "w");
putc(0, fptr);
putc(0, fptr);
putc(2, fptr); /* uncompressed RGB */
putc(0, fptr); putc(0, fptr);
putc(0, fptr); putc(0, fptr);
putc(0, fptr);
putc(0, fptr); putc(0, fptr); /* X origin */
putc(0, fptr); putc(0, fptr); /* y origin */
putc((width & 0x00FF), fptr);
putc((width & 0xFF00) / 256, fptr);
putc((height & 0x00FF), fptr);
putc((height & 0xFF00) / 256, fptr);
putc(bitsPerPixel, fptr); /* 24/32 bit bitmap */
putc(bitsAlphaChannel, fptr); /* When 32 bit, write 8, else 0 */
auto pixelData = refTGA.GetPixels();
for (size_t i = 0; i < static_cast<size_t>(width) * static_cast<size_t>(height) * (bitsPerPixel/8); i += (bitsPerPixel/8))
{
unsigned char r = pixelData[i];
unsigned char g = pixelData[i + 1];
unsigned char b = pixelData[i + 2];
unsigned char a = (bitsAlphaChannel == 8 ? pixelData[i + 3] : 0);
putc(b, fptr);
putc(g, fptr);
putc(r, fptr);
if (bitsAlphaChannel == 8)
putc(a, fptr);
}
fclose(fptr);
}
//=========================================
// main
//=========================================
int main()
{
Tga oTgaA("tileA.tga");
writeTGA("tileA_new.tga", oTgaA); // works correct as aspected
Tga oTgaB("tileB.tga");
writeTGA("tileB_new.tga", oTgaB); // graphic-file has artefacts, why?
}
Since my comment seems to have solved the problem (see above ^^^^). I'll expand here.
There is a significant difference on Windows (with at least Microsoft's CRT) between writing a file in text mode and writing in binary mode.
Specifically any character that matches '\n' will be expanded into the two character sequence "\r\n". Further certain functions apply conversions between MB and unicode characters. More information can be in the MSDN documentation on fopen
accessible at: https://msdn.microsoft.com/en-us/library/yeby3zcb.aspx
Therefore when reading/writing non-textual data be sure to pass "rb"
or "wb"
flags to fopen
as appropriate.
On Posix systems this consideration does not apply however it is still good practice to make your intent clear.