【问题标题】:Skip over padding in a bitmap-to-string converter?跳过位图到字符串转换器中的填充?
【发布时间】:2013-02-23 02:12:39
【问题描述】:

我有以下算法用于将 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);
}

问题是,我希望它忽略每行末尾的填充。例如,对于一个 2x2 位图,其中所有像素的值为 #7f7f7f,out.txt 的内容也包含填充字节:

7F7F7F7F7F7F00007F7F7F7F7F7F0000

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

【问题讨论】:

    标签: c windows file-io bitmap padding


    【解决方案1】:

    将您的项目设置更改为在写入时不填充到 16 个字节是一种想法。另一个是知道填充设置的字节数(在您的示例中为 16),并使用模数(或和)来确定每行需要跳过多少字节:

      int offset = 0;
      for(i = 0; i &lt height; i++)
      {
        // only read 3 sets of bytes as the 4th is padding.
        for(j = 0; j &lt 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;
      }
    
    

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

    【讨论】:

    • 每一行都是DWORD 对齐的。也就是说,如果每行的像素数不是 4 的倍数,则每行的末尾将用 0 填充,直到row_length_in_bytes%8==0,在位图的下一行开始之前。
    猜你喜欢
    • 2014-05-23
    • 2020-05-31
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2011-07-01
    • 2010-11-24
    相关资源
    最近更新 更多