简单读取然后写入.bmp文件C代码

时间:2017-07-13 00:05:16

标签: c file image-processing bmp

我正在尝试对.bmp文件进行简单读取,然后输出相同的.bmp文件。现在,它仅在宽度和高度完全相同时才有效。这是我的问题的一个很好的指标,但我似乎无法弄明白。我正在寻找你们可能有的任何想法或建议。还有其他问题,但它们似乎并不完全是我正在寻找的。但是,当宽度和高度不同时,我的输出类似于此处显示的输出Read/Write SImple BMP Image C++ - 基本上它是偏斜的,不完整的和重复的,而不是实际的图像。

以下是我在.bmp文件中读取的代码:

    bool LoadBmp(const char *filepath)
    {
        FILE *f = fopen(filepath, "rb");
        if (f)
        {
          Bwidth = 0;
          Bheight = 0;
          pixels = NULL;
          unsigned char info[54] = {0};
          fread(info, sizeof(unsigned char), 54, f);
          Bwidth = *(unsigned int *)&info[18];
          Bheight = *(unsigned int *)&info[22];
          unsigned int size = Bwidth * Bheight * 3; // ((((Bwidth * Bheight) + 31) & ~31) / 8) * Bheight;
          pixels = malloc(size);
          fread(pixels, sizeof(unsigned char), size, f);
          fclose(f);
          return true;
       }  
       return false;
   }

请注意,我不确定是否要在下面创建大小(Bwidth * Bheight * 3)或使用注释掉的内容。另请注意,'Bwidth'和'Bheight'声明为unsigned int,而'pixels'定义为unsigned char *。另外,我故意不使用结构来存储.bmp文件数据。

这是我用来编写刚刚加载的.bmp文件的代码:

    static bool WriteBMP(int x, int y, unsigned char *bmp, char * name)
    {
      const unsigned char bmphdr[54] = {66, 77, 255, 255, 255, 255, 0, 0, 0, 0, 54, 4, 0, 0, 40, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 1, 0, 8, 0, 0, 0, 0, 0, 255, 255, 255, 255, 196, 14, 0, 0, 196, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
      unsigned char hdr[1078];
      int i, j, c, xcorr, diff;
      FILE *f;

      xcorr = (x+3) >> 2 << 2;  // BMPs have to be a multiple of 4 pixels wide.
      diff = xcorr - x;

      for (i = 0; i < 54; i++) hdr[i] = bmphdr[i];
      *((int*)(&hdr[18])) = xcorr;
      *((int*)(&hdr[22])) = y;
      *((int*)(&hdr[34])) = xcorr*y;
      *((int*)(&hdr[2])) = xcorr*y + 1078;
      for (i = 0; i < 256; i++) {
        j = i*4 + 54;
        hdr[j+0] = i;  // blue
        hdr[j+1] = i;  // green
        hdr[j+2] = i;  // red
        hdr[j+3] = 0;  // dummy
      }

      f = fopen(name, "wb");
      if (f) {
          assert(f != NULL);
          c = fwrite(hdr, 1, 1078, f);
          assert(c == 1078);
          if (diff == 0) {
            c = fwrite(bmp, 1, x*y, f);
            assert(c == x*y);
          } else {
            *((int*)(&hdr[0])) = 0;  // need up to three zero bytes
            for (j = 0; j < y; j++) {
              c = fwrite(&bmp[j * x], 1, x, f);
              assert(c == x);
              c = fwrite(hdr, 1, diff, f);
              assert(c == diff);
            }
          }
          fclose(f);
          return true;
      }
      else return false;
    }

提前感谢您的帮助。我很感激你的时间!

0 个答案:

没有答案