【问题标题】:Load Custom Image Format C/C++ Binary加载自定义图像格式 C/C++ 二进制
【发布时间】:2012-03-09 23:10:23
【问题描述】:

我在尝试加载图像文件 (PIXELIMAGEFORMAT) 时遇到了很多问题。该代码无法通过将魔术头值与PIXELIMAGEFORMAT 进行比较(没有字符串结尾字符)

我的图片格式是:

Bytes   0-15: PIXELIMAGEFORMAT (The Magic Header Value)
Bytes  16-17: Width            (Formatted as 0000 xxxx xxxx xxxx)
Bytes  18-19: Height           (Formatted as 0000 xxxx xxxx xxxx)
Bytes  20-23: Bits Per Pixel   (Formatted as 1000 1000 1000 1000)
Bytes  24-31: NULL             (All 0's)
Bytes 32-END: 32-Bit RGBA      (8 Bit Red, 8 Bit Green, 8 Bit Blue, 8 Bit Alpha) 

我的图片加载代码是:

char* vimg_LoadPIXELIMAGE(char* filePath) {
  FILE* file;
  file = fopen(filePath, "rb");
  if (file == NULL) return "a";

  char* header = (char*)malloc(32);
  fread(header, sizeof(char), 32, file);
  char* magicHeader = (char*)malloc(16);
  const char magic[] = {
    'P', 'I', 'X', 'E', 'L',
    'I', 'M', 'A', 'G', 'E',
    'F', 'O', 'R', 'M', 'A', 'T'
  };
  strncpy(magicHeader, header, 16);

  if (magicHeader != magic) return "b";

  unsigned short width;
  unsigned short height;

  memcpy(&width, header + 16, 2);
  memcpy(&height, header + 18, 2);

  unsigned int fileSize = width * height;

  char* fullbuffer = (char*)malloc(fileSize+32);
  char* buffer = (char*)malloc(fileSize);
  fread(fullbuffer, 1, fileSize + 32, file);
  memcpy(buffer, fullbuffer + 32, fileSize);

  return buffer;
}

我的主要功能是:

void main(int argc, char* argv) {
  char* imgSRC;
  imgSRC = vimg_LoadPIXELIMAGE("img.pfi");
  if (imgSRC == "a")
    printf("File Is Null!\n");
  else if (imgSRC == "b")
    printf("File Is Not a PIXELIMAGE!\n");
  else if (imgSRC == NULL)
    printf("SEVERE ERROR!!!\n");
  else
    printf(imgSRC);
  system("pause");
}

目前它应该做的是打印出每个二进制像素的字符值。

如果你愿意,我也可以发布我当前的图像文件。

谢谢!

  • 阿德里安·科拉多

【问题讨论】:

    标签: c image memory binary


    【解决方案1】:

    你比较的是缓冲区的地址,而不是缓冲区本身,你应该使用memcmp

    if (memcmp(magicHeader, magic, 16) != 0) return "b";
    

    这不是答案,但也应该考虑:

    你比较地址,而你应该比较值:

    if (*imgSRC == 'a')
    

    另外,由于可能会返回 NULL,我会更改检查的顺序:

    if (imgSRC == NULL)
        printf("SEVERE ERROR!!!\n");
    else if (*imgSRC == 'a')
        printf("File Is Null!\n");
    else if (*imgSRC == 'a')
        printf("File Is Not a PIXELIMAGE!\n");
    else
        printf(imgSRC);
    

    【讨论】:

    • 那行不通,因为*imgSRC 是内存位置。 imgSRC 是一个字符数组。无论如何,这不是错误所在。比较magicHeadermagic 时会出现错误,这两个DO 具有相同的值...
    • 另外.. NULL 没有特别返回......它是作为防止尝试打印空值的保护措施。每次我运行代码时,它都会打印“文件不是像素图像!”字符串。
    • 修复了 File is Not a PIXELIMAGE 错误,但现在我只需要找出文件未正确加载的原因。猜猜是时候进行实验了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2016-02-21
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多