c - 跳过位图到字符串转换器中的填充?

标签 c windows file-io bitmap padding

我使用以下算法将 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

如何调整循环以避免包含填充零?

最佳答案

将项目设置更改为写入时不填充到 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;
  }

这个解决方案应该有效,但如果没有进一步了解您的填充字节是如何发生的,我不会保证它。

关于c - 跳过位图到字符串转换器中的填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15278657/

相关文章:

C宏扩展成多个函数定义

c++ - 从 C 程序调用的 C++ 库中的新建和删除

c - 从 Windows gui 程序输出到命令行

c++ - 在 Windows 7/8/Store C++ 中播放内存中的压缩音频

javascript - SAS 打印到文件

c - 使用 MPI_Wait 获得的 MPI_Isend 状态有什么用?

c - 一次将数据写入多个套接字(一个系统调用)

windows - 如何回复快速 javascript 测试

C# File.ReadAllLines 不中断换行

c++ - 执行系统命令很慢