我有以下算法将24位位图转换为由它组成的像素的十六进制字符串表示:
// *data = previously returned data from a call to GetDIBits
// width = width of bmp
// height = height of bmp
void BitmapToString(BYTE *data, int width, int height)
{
int total = 4*width*height;
int i;
CHAR buf[3];
DWORD dwWritten = 0;
HANDLE hFile = CreateFile(TEXT("out.txt"), GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
for(i = 0; i < total; i++)
{
SecureZeroMemory(buf, 3);
wsprintfA(buf, "%.2X", data[i]);
// only write the 2 characters and not the null terminator:
WriteFile(hFile, buf, 2, &dwWritten, NULL);
}
WriteFile(hFile, "\0", 2, &dwWritten, NULL);
CloseHandle(hFile);
}
问题是,我希望它忽略每行末尾的填充。例如,对于所有像素值为#7f7f7f的2x2位图,out.txt的内容也包含填充字节:
7F7F7F7F7F7F00007F7F7F7F7F7F0000
如何调整循环以避免包含填充零?
答案 0 :(得分:1)
在写入时将项目设置更改为不填充到16个字节是一个想法。另一个是知道pad设置的字节数(在你的例子中为16),并使用模数(或和)来确定每行需要跳过多少字节:
int offset = 0;
for(i = 0; i < height; i++)
{
// only read 3 sets of bytes as the 4th is padding.
for(j = 0; j < width*3; j++)
{
SecureZeroMemory(buf, 3);
wsprintfA(buf, "%.2X", data[offset]);
// only write the 2 characters and not the null terminator:
WriteFile(hFile, buf, 2, &dwWritten, NULL);
offset++;
}
// offset past pad bytes
offset += offset % 8;
}
这个解决方案应该可行,但我不会在没有进一步了解你的pad字节的情况下保证它。