我正在尝试读取我在Paint.net中创建的文件的TGA标题。似乎它有问题。如果我使用规范中的头结构,就像这样:
typedef struct {
CHAR idlength;
CHAR colourmaptype;
CHAR datatypecode;
WORD colourmaporigin;
WORD colourmaplength;
CHAR colourmapdepth;
WORD x_origin;
WORD y_origin;
WORD width;
WORD height;
CHAR bitsperpixel;
CHAR imagedescriptor;
} TGAHEADER;
我明白了:
Data size: 0
Color Map type: 0
Data Type code: 2
Bits per-pixel: 0
Size: 501 x 2080
哪个错误,因为我的图像是501x501,每像素32位。但是,如果我从结构中注释掉两个字节,那么f.e.这一个colourmaporigin
,我明白了:
Data size: 0
Color Map type: 0
Data Type code: 2
Bits per-pixel: 32
Size: 501 x 501
哪个是对的。我正在阅读我在此文件格式中找到的所有内容。它永远不会说任何这些字段都是可选的或其他东西。
为什么我会得到这样的结果?
以下是读取数据的代码:
void Image::readTGA()
{
TGAHEADER fileHeader;
std::ifstream fileHandle(fileName, std::ios::binary);
if (fileHandle.is_open())
{
fileHandle.read((char*)(&fileHeader), sizeof(TGAHEADER));
fileHandle.close();
}
else
{
std::cout << "An error occured when opening a file." << std::endl;
}
}
我正在使用VS2015,目标是x86平台。
答案 0 :(得分:2)
这是一个填充问题。使用Visual Studio,您可以使用#pragma pack(1)
编译器指令禁用任何结构填充。
<强>示范强>
#include<stdio.h>
#include<windows.h>
// Default packing of structure with padding
typedef struct {
CHAR idlength;
CHAR colourmaptype;
CHAR datatypecode;
WORD colourmaporigin;
WORD colourmaplength;
CHAR colourmapdepth;
WORD x_origin;
WORD y_origin;
WORD width;
WORD height;
CHAR bitsperpixel;
CHAR imagedescriptor;
} TGAHEADER;
#pragma pack(1) // structure fields are aligned to byte boundary (no padding)
typedef struct {
CHAR idlength;
CHAR colourmaptype;
CHAR datatypecode;
WORD colourmaporigin;
WORD colourmaplength;
CHAR colourmapdepth;
WORD x_origin;
WORD y_origin;
WORD width;
WORD height;
CHAR bitsperpixel;
CHAR imagedescriptor;
} TGAHEADER_PACKED;
int main()
{
printf("Offset of field bitsperpixel in TGAHEADER structure %d\n", offsetof(TGAHEADER, bitsperpixel));
printf("Offset of field bitsperpixel in packed TGAHEADER structure %d\n", offsetof(TGAHEADER_PACKED, bitsperpixel));
}
输出:
Offset of field bitsperpixel in TGAHEADER structure 18
Offset of field bitsperpixel in packed TGAHEADER structure 16