【问题标题】:not able to save an image file using c?无法使用 c 保存图像文件?
【发布时间】:2013-01-16 18:26:28
【问题描述】:

我试图将一个 bmp 图像克隆到另一个 bmp 图像中,但最终图像无法打开。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <process.h>

void readBMP(char* filename) {
int i;
FILE* f = fopen(filename, "rb");
FILE* f1= fopen("save.bmp", "wb");
if (!f) {
    printf("Could not read file!\n");
    exit(0);
}
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f);
int width  = *(int*)&info[18];
int height = *(int*)&info[22];
printf("%d %d\n", width, height);

fwrite(info, sizeof(unsigned char), 54, f1);

int length = width * height;
unsigned int image[10000][3];

for(i = 0; i < length; i++) {
    image[i][2] = getc(f);
    image[i][1] = getc(f);
    image[i][0] = getc(f);

    putc(image[i][2], f1);
    putc(image[i][1], f1);
    putc(image[i][0], f1);

    printf("pixel %d : [%d,%d,%d]\n", i+1, image[i][0], image[i][1], image[i][2]);
}
fclose(f);
fclose(f1);
}
void main() {
char* fileName = "bitgray.bmp";
readBMP(fileName);
getch();
}

我作为输入的图像是 114X81,大小为 27918 字节。 最终图像大小相同,但大小为 27756 字节。

可能是什么错误??

【问题讨论】:

  • 你怎么知道你遇到了错误? fopen() 失败了吗?程序崩溃了吗? save.bmp 文件是否出现在您的目录中但无法读取?
  • 长度不是宽度*高度那么简单。
  • 您应该检查文件 f1 的 fopen 结果。

标签: c image-processing bmp


【解决方案1】:

BMP 将每一行存储在multiple of 4 bytes 中。在您的情况下,这意味着每行占用 116 个字节(2 个字节填充)。这给出了 116x78x3+54=27198 所以你做错了。

顺便说一句,标头长度并不总是 54 字节。

【讨论】:

  • 但我在某处读到 24 位 bmp 图像的标头长度为 54,然后是所有像素值...
  • 对于大多数 24 位 BMP,您会发现,这是真的。我想这对你的场景来说已经足够了。
  • 我应该使用unsigned long int 来获取 4 个字节吗?或者可能有其他方法来获得所需的填充?
  • 有什么问题?读取 116 个字节而不是 114 个字节,仅此而已。
  • 顺便说一句,将字节存储在矩阵中并同时将其再次写入文件是相当不寻常的。 BTW2:我宁愿在每个迭代循环中将每一行直接读入矩阵。
【解决方案2】:

BMP 图像需要填充,因此每行是 4 字节的倍数。

您的行不是 4 的倍数,因此每行缺少 2 个字节,或总共 162 个字节 - 这是大小上的差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2011-01-18
    相关资源
    最近更新 更多