首页 > 解决方案 > 使用 c 生成单色位图图像

问题描述

我正在编写代码以从数组中生成单色 bmp 图像。有很多工具可以生成 bmp 到数组,但我希望它以相反的方式。我发现了很多代码,但它是彩色图像。这是我正在尝试的代码...

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <malloc.h>
#define _height 64
#define _width 128
#define _bitsperpixel 1
#define _planes 1
#define _compression 0
#define _pixelbytesize _height*_width*_bitsperpixel/8
#define _filesize _pixelbytesize+sizeof(bitmap)
#define _xpixelpermeter 0x130B //2835 , 72 DPI
#define _ypixelpermeter 0x130B //2835 , 72 DPI
#define pixel 0x55
#pragma pack(push,1)

unsigned char arr[8192]={0};

typedef struct{
    uint8_t signature[2];
    uint32_t filesize;
    uint32_t reserved;
    uint32_t fileoffset_to_pixelarray;
} fileheader;
typedef struct{
    uint32_t dibheadersize;
    uint32_t width;
    uint32_t height;
    uint16_t planes;
    uint16_t bitsperpixel;
    uint32_t compression;
    uint32_t imagesize;
    uint32_t ypixelpermeter;
    uint32_t xpixelpermeter;
    uint32_t numcolorspallette;
    uint32_t mostimpcolor;
} bitmapinfoheader;
typedef struct {
    fileheader fileheader;
    bitmapinfoheader bitmapinfoheader;
} bitmap;
#pragma pack(pop)

int main (int argc , char *argv[]) {
int i;
    FILE *fp = fopen("test.bmp","wb");
    bitmap *pbitmap  = (bitmap*)calloc(1,sizeof(bitmap));
    uint8_t *pixelbuffer = (uint8_t*)malloc(_pixelbytesize);
    strcpy(pbitmap->fileheader.signature,"BM");
    pbitmap->fileheader.filesize = _filesize;
    pbitmap->fileheader.fileoffset_to_pixelarray = sizeof(bitmap);
    pbitmap->bitmapinfoheader.dibheadersize =sizeof(bitmapinfoheader);
    pbitmap->bitmapinfoheader.width = _width;
    pbitmap->bitmapinfoheader.height = _height;
    pbitmap->bitmapinfoheader.planes = _planes;
    pbitmap->bitmapinfoheader.bitsperpixel = _bitsperpixel;
    pbitmap->bitmapinfoheader.compression = _compression;
    pbitmap->bitmapinfoheader.imagesize = _pixelbytesize;
    pbitmap->bitmapinfoheader.ypixelpermeter = _ypixelpermeter ;
    pbitmap->bitmapinfoheader.xpixelpermeter = _xpixelpermeter ;
    pbitmap->bitmapinfoheader.numcolorspallette = 0;
    fwrite (pbitmap, 1, sizeof(bitmap),fp);
    for(i=0;i<8192;i++)
    {
    pixelbuffer[i] = arr[i];
}
 //   memset(pixelbuffer,pixel,_pixelbytesize);
    fwrite(pixelbuffer,1,_pixelbytesize,fp);
    fclose(fp);
    free(pbitmap);
    free(pixelbuffer);
}

我给每个像素的位数是 1 位(我想要黑色或白色),并且不确定必须更改的其他参数。

如果我将 _bitsperpixel 用作 24,那么它工作正常,但如果我指定为 1,那么它就会崩溃..

标签: cbitmapbmp

解决方案


什么时候_bitsperpixel == 1,那么_pixelbytesize == 1024。您的循环运行 until 8192,因此写入超出分配的内存。

根据您在 中存储的内容arr,您应该将循环的迭代次数减少到_pixelbytesize,或者将字节转换arr为位:

for(int i = 0; i < _pixelbytesize; ++i)
{
    uint8_t b = 0;
    for(int j = 0; j < 8; ++j)
        b |= arr[8*i + j] >> 7 << j;
    pixelbuffer[i] = b;
}

请注意,这是一个简单的代码,仅适用于可被 8 整除的图像宽度。


推荐阅读