c - C 语言中的位图 8 位灰度图像

标签 c bitmap grayscale

我正在尝试用 C 创建位图灰度图像。问题是每像素位数,如果我将其设置为 24 => 3 字节,它可以工作,但给我彩色图像。我想将其设置为 8 => 1 字节,以便生成灰度图像。

#include<stdio.h>
main() {
    char bitmap[1000];
    FILE *bp;

    // -- FILE HEADER -- //

   // bitmap signature
   bitmap[0] = 0x42; // B
   bitmap[1] = 0x4d; // M

   // file size
   bitmap[2] = 0x86; // 40 + 14 + 12 (134-66) = 68
   bitmap[3] = 0;
   bitmap[4] = 0;
   bitmap[5] = 0;

   // reserved field (in hex. 00 00 00 00)
   for (int i = 6; i < 10; i++) bitmap[i] = 0;

    bitmap[10] = 54; // 54-36

   // offset of pixel data inside the image
   for (int i = 11; i < 14; i++) bitmap[i] = 0;

    // -- BITMAP HEADER -- //

    // header size
    bitmap[14] = 0x28; // 40
    for (int i = 15; i < 18; i++) bitmap[i] = 0;

    // width of the image
    bitmap[18] = 4; // 5
    for (int i = 19; i < 22; i++) bitmap[i] = 0;

    // height of the image
    bitmap[22] = 1; // 5
    for (int i = 23; i < 26; i++) bitmap[i] = 0;

    // reserved field
    bitmap[26] = 1;
    bitmap[27] = 0;

    // number of bits per pixel
    bitmap[28] = 24; // 3 byte 24
    bitmap[29] = 0;

    // compression method (no compression here)
    for (int i = 30; i < 34; i++) bitmap[i] = 0;

    // size of pixel data
    bitmap[34] = 24; // 12 bits => 4 pixels 80
    bitmap[35] = 0;
    bitmap[36] = 0;
    bitmap[37] = 0;

    // horizontal resolution of the image - pixels per meter (2835)
    bitmap[38] = 0;
    bitmap[39] = 0;
    bitmap[40] = 0xC4; //48
    bitmap[41] = 0x0E; //177

    // vertical resolution of the image - pixels per meter (2835)
    bitmap[42] = 0;
    bitmap[43] = 0;
    bitmap[44] = 0xC4;
    bitmap[45] = 0x0E;

    // color pallette information
    for (int i = 46; i < 48; i++) bitmap[i] = 0;

    // color pallette information
    for (int i = 48; i < 50; i++) bitmap[i] = 0;

    // number of important colors
    for (int i = 50; i < 52; i++) bitmap[i] = 0;

    // number of important colors
    for (int i = 52; i < 54; i++) bitmap[i] = 0;

    // -- PIXEL DATA -- //
    for (int i = 54; i < 134; i++){
    if ( i %2 == 0)
        bitmap[i] = 0xFF;
    else bitmap[i] = 0;
    }
    /*bitmap[54] =1; bitmap[55] = 1; bitmap[56] = 0;
    bitmap[57] = 1; bitmap[58] = 1; bitmap[59] = 0;
    bitmap[60] = 1; bitmap[61] = 1; bitmap[62] = 0;
    bitmap[63] = 1; bitmap[64] = 1; bitmap[65] = 0;*/

    bp = fopen("e://binary.bmp", "wb");
    for (int i = 0; i < 134; i++) {
        fprintf(bp, "%c", bitmap[i]);
    }
    fclose(bp);

}

最佳答案

设置 BitsPerPixel= 8 并让 header 后跟定义灰度渐变的 256 个 RGBQUAD 条目。

关于c - C 语言中的位图 8 位灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35956721/

相关文章:

c++ - 将 PNG 类型资源转换为 cv::Mat 时的 CreateDIBSection ERROR_TAG_NOT_FOUND

image - 灰度图像和二值图像有什么区别吗?

Cuda内核没有并发运行

c - 如果您的指针变得垃圾,如何制作 if 语句

bitmap - 如何将图像转换为每像素 2 位?

android - 使用 Renderscript 和超过 25 个半径的 Android 模糊位图

java - 如何获取灰度图像中的像素值

c - C语言读取并显示灰度图像。

c - 使用 b^n 次方求矩阵的逆

c - 按特定字段对二维字符串数组进行排序