C语言读写单通道BMP灰度图像

1.BMP格式


2.文件读取思路(单通道)

bmp头部信息54字节;
1.读取文件头(14 Byte)
2.读取文件头信息(40 Byte)
3.解析图像大小(宽度x高度),读取数据偏移量;
4.分配内存数据和文件头,读取所有文件头及数据;
5.保存时直接存入文件头及修改后的数据。

3.代码

读文件:(molloc后需要释放内存)

unsigned char bmpHeader[14];
unsigned char bmpInfoHeader[40];
unsigned char bmpHeaderAll[54]; // 前54个字节是bmp文件头
FILE *file = fopen("D:\\Code\\VSCode\\Ccode\\Canny\\images\\input\\input1_gray.bmp", "rb");
    if (file == NULL)
    {
        printf("无法打开文件\n");
        return 1;
    }
    fread(bmpHeader, sizeof(unsigned char), 14, file);
    fread(bmpInfoHeader, sizeof(unsigned char), 40, file);
    int width = *(int *)&bmpInfoHeader[4];
    int height = *(int *)&bmpInfoHeader[8];
    int pixelDataOffset = *(int *)&bmpHeader[10];
    short int pixelData = *(short int *)&bmpInfoHeader[14];
    printf("width=%d,heigth=%d,offset=%d,rgb=%d\n", width, height, pixelDataOffset, pixelData);
    // 读取文件头
    unsigned char *head = (unsigned char *)malloc(pixelDataOffset * sizeof(unsigned char)); // 用来存储bmp文件头,不一定是54个字节
    fseek(file, 0, SEEK_SET);                                                               // 文件的开头开始计算偏移量。
    fread(head, sizeof(unsigned char), pixelDataOffset, file);                              // 读取文件头,保存时用到
    // 读取图像数据
    fseek(file, pixelDataOffset, SEEK_SET); // 文件的开头开始计算偏移量。
    unsigned char *imageData = (unsigned char *)malloc(width * height * sizeof(unsigned char));
    fread(imageData, sizeof(unsigned char), width * height, file);
    fclose(file);
    // 释放内存
    free(imageData);
    free(head);
    free(out);
    free(out1);

写文件:

void writeFile(unsigned char *filename, unsigned char *data, unsigned char *head, int width, int height, int pixelDataOffset)
{
    FILE *newFile = fopen(filename, "wb"); //"D:\\Code\\VSCode\\Ccode\\Canny\\modified_image3_k5_100_sobel.bmp"
    if (newFile == NULL)
    {
        printf("can't create file\n");
        return;
    }
    fwrite(head, sizeof(unsigned char), pixelDataOffset, newFile);
    fwrite(data, sizeof(unsigned char), width * height, newFile);
    fclose(newFile);
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇