问题
I tried to clone a bmp image into another bmp image but the final image would not open.
#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();
}
The image that I took as an input was 114X81 with size of 27918 bytes. The final image had same size but the size was 27756 bytes.
What could be the error ??
回答1:
BMP stores each row in a multiple of 4 bytes. In your case, that means that each rows takes 116 bytes, (2 bytes padding). That gives 116x78x3+54=27198 So you are doing it wrong.
BTW the header length not always is 54 bytes.
回答2:
BMP images need padding so each line is a multiple of 4 bytes.
Your lines are not a multiple of 4, so you're missing 2 bytes per line, or 162 in total - which is the difference in size.
来源:https://stackoverflow.com/questions/14365182/not-able-to-save-an-image-file-using-c