c 生成BMP图片
c 生成BMP图片
typedef struct __attribute__((packed)){
// Bytes 0-1: Signature "BM" (0x42 0x4D)
// Bytes 2-5: FileSize (uint32, little-endian)
// Bytes 6-9: Reserved (always 0)
// Bytes 10-13: Offset (uint32, offset to pixel data from file start)
uint16_t signature ;
uint32_t fileSize;
int32_t reserved;
uint32_t offset;
} BmpHerder;
typedef struct
{
//Bytes 0-3: HeaderSize (40)
// Bytes 4-7: Width (int32, pixels)
// Bytes 8-11: Height (int32, pixels; negative means top-down)
// Bytes 12-13: Planes (1)
// Bytes 14-15: BitCount (1, 4, 8, 16, 24, or 32)
// Bytes 16-19: Compression (0 = none, 1 = RLE8, 2 = RLE4, 3 = bitfields)
// Bytes 20-23: ImageSize (0 if uncompressed)
// Bytes 24-27: XpixelsPerMeter (physical resolution)
// Bytes 28-31: YpixelsPerMeter (physical resolution)
// Bytes 32-35: ColorsUsed (0 means 2^BitCount)
// Bytes 36-39: ColorsImportant (0 means all)
int32_t headerSize ;
int32_t width ;
int32_t height ;
uint16_t planes ;
uint16_t bitCount ;
int32_t compression ;
int32_t imageSize ;
int32_t xpixelsPerMeter ;
int32_t ypixelsPerMeter ;
int32_t colorsUsed ;
int32_t colorsImportant ;
}BmpInfoHerder;
BmpHerder bmpHerder = {0};
BmpInfoHerder bmpInfoHerder = {0};
int generateBmp(){
int width = 50;
int height = 50;
int dataSize = width * height *3;
char *buf = av_malloc(dataSize);
int index = 0;
for (int i = 0; i < height; i++)
{
printf("rand;%d,%d\n",rand() % 255,rand());
for (int n = 0; n < width; n++)
{
buf[index+ 0] = rand() % 255;
buf[index+1] = rand() % 255;
buf[index + 2] = rand() % 255;
index += 3;
}
}
FILE *f;
f = fopen("test3.bmp","wb");
// fprintf(f,"P5\n%d %d\n%d\n",width,height,255);
bmpHerder.fileSize = sizeof(BmpHerder) + sizeof(BmpInfoHerder) + dataSize;
bmpHerder.offset = sizeof(BmpHerder) + sizeof(BmpInfoHerder);
bmpHerder.signature = 0x4d42; //bm
bmpHerder.reserved = 0;
// bmpHerder.signature = 0x424D;
bmpInfoHerder.headerSize = sizeof(BmpInfoHerder);
bmpInfoHerder.width = width;
bmpInfoHerder.height = -height ;
bmpInfoHerder.planes =1;
bmpInfoHerder.bitCount =24;
bmpInfoHerder.compression =0;
bmpInfoHerder.imageSize =0;
bmpInfoHerder.xpixelsPerMeter =0;
bmpInfoHerder.ypixelsPerMeter =0;
bmpInfoHerder.colorsImportant =0;
bmpInfoHerder.colorsUsed =0;
// bmpInfoHerder.
fwrite(&bmpHerder,sizeof(BmpHerder),1,f);
fwrite(&bmpInfoHerder,sizeof(BmpInfoHerder),1,f);
fwrite(buf,dataSize,1,f);
fclose(f);
av_free(buf);
return 0;
}
调用执行
generateBmp();
fileHerder 要加
__attribute__((packed)) 不然会对不齐,打不开图片,
参考:
https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapfileheader
https://file-convert-factory.org/zh-Hans/blog/bmp-format-deep-dive
https://www.cnblogs.com/wurui1994/p/5965920.html
https://www.cnblogs.com/kendoziyu/p/16551501.html
浙公网安备 33010602011771号