C++ 将像素信息转为bmp图片存储

// 定义BMP 的头数据
typedef struct /**** BMP file header structure ****/
{
  unsigned int bfSize;        /* Size of file */
  unsigned short bfReserved1; /* Reserved */
  unsigned short bfReserved2; /* ... */
  unsigned int bfOffBits;     /* Offset to bitmap data */
} MyBITMAPFILEHEADER;

typedef struct /**** BMP file info structure ****/
{
  unsigned int biSize;         /* Size of info header */
  int biWidth;                 /* Width of image */
  int biHeight;                /* Height of image */
  unsigned short biPlanes;     /* Number of color planes */
  unsigned short biBitCount;   /* Number of bits per pixel */
  unsigned int biCompression;  /* Type of compression to use */
  unsigned int biSizeImage;    /* Size of image data */
  int biXPelsPerMeter;         /* X pixels per meter */
  int biYPelsPerMeter;         /* Y pixels per meter */
  unsigned int biClrUsed;      /* Number of colors used */
  unsigned int biClrImportant; /* Number of important colors */
} MyBITMAPINFOHEADER;

void MainWindow::creat_bmp(unsigned char *rgb, const char *bmp_file) {

//尺寸根据图片大小而定
  char buf[480][640][3] = {0};
  int width = 640;
  int height = 480;
  MyBITMAPFILEHEADER bfh;
  MyBITMAPINFOHEADER bih;

  unsigned short bfType = 0x4d42;
  bfh.bfReserved1 = 0;
  bfh.bfReserved2 = 0;
  bfh.bfSize = 2 + sizeof(MyBITMAPFILEHEADER) + sizeof(MyBITMAPINFOHEADER) +
               width * height * 3;
  bfh.bfOffBits = 0x36;

  bih.biSize = sizeof(MyBITMAPINFOHEADER);
  bih.biWidth = width;
  bih.biHeight = height;
  bih.biPlanes = 1;
  bih.biBitCount = 24;
  bih.biCompression = 0;
  bih.biSizeImage = 0;
  bih.biXPelsPerMeter = 5000;
  bih.biYPelsPerMeter = 5000;
  bih.biClrUsed = 0;
  bih.biClrImportant = 0;
  FILE *file = fopen(bmp_file, "wb");
  if (!file) {
    printf("Could not write file\n");
    return;
  }

//根据图片像素修改
  int i, j, k;


  for (i = 479; i >= 0; i--) {
    for (j = 0; j < 640; j++) {
      for (k = 2; k >= 0; k--) {
        buf[i][j][k] = *rgb;
        rgb++;
      }
    }
  }

  fwrite(&bfType, sizeof(bfType), 1, file);
  fwrite(&bfh, sizeof(bfh), 1, file);
  fwrite(&bih, sizeof(bih), 1, file);

  fwrite(buf, width * height * 3, 1, file);
  fclose(file);
}

你可能感兴趣的:(c++,c++,开发语言)