我有一個項目,涉及將一個.bmp文件讀入C程序,在其上放置一個掩碼,並將該掩碼的版本打印回不同的文件。我遇到問題的部分似乎是在文件中讀取的實際過程。我看到的第一個大紅旗是它一直以錯誤的分辨率閱讀。我搜索了很多,並看到一些腳本可以在.bmp文件中讀取,作爲各種問題的答案,但是使用這些腳本中的邏輯沒有幫助。C錯誤讀取.bmp文件的分辨率
主要問題似乎是,而不是閱讀我的教授給出的示例圖像上200×300的正確尺寸,它讀入13107200 x 65536.但是,如果我要包含部分代碼打印到不同的文件,您會看到輸出文件具有適當的分辨率。這告訴我,我很可能正確閱讀信息,但沒有按照我認爲的方式存儲它。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct HEADER {
unsigned short int Type; // Magic indentifier
unsigned int Size; // File size in bytes
unsigned short int Reserved1, Reserved2;
unsigned int Offset; // Offset to data (in B)
} Header; // -- 14 Bytes
struct INFOHEADER {
unsigned int Size; // Header size in bytes
int Width, Height; // Width/height of image
unsigned short int Planes; // Number of colour planes
unsigned short int Bits; // Bits per pixel
unsigned int Compression; // Compression type
unsigned int ImageSize; // Image size in bytes
int xResolution, yResolution; // Pixels per meter
unsigned int Colors; // Number of colors
unsigned int ImportantColors; // Important colors
} InfoHeader; // -- 40 Bytes
struct PIXEL {
unsigned char Red, Green, Blue; // Intensity of Red, Green, and Blue
}; // -- 3 Bytes
int getFileSize(FILE *input);
int getHexVal(FILE *input);
struct HEADER *getHeader(FILE *input);
struct INFOHEADER *getInfoHeader(FILE *input);
struct PIXEL *getPixel(FILE *input, struct PIXEL *loc);
struct HEADER *printHeader(FILE *output);
struct INFOHEADER *printInfoHeader(FILE *output);
struct PIXEL *printPixel(FILE *output, struct PIXEL *loc);
int main(int argc, char const *argv[]) {
if (argc == 3) {
if (!strcmp(argv[1], argv[2])) {
printf("The input and output file must be different. Please try again.\n");
return 1;
}
// char Matrix[3][3] =
// { { 0, -1, 0 },
// { -1, 4, -1 },
// { 0, -1, 0 }
// };
FILE *input = fopen(argv[1], "rb");
if (!input) return 1;
int i, j;
// getHeader(input);
fread(&Header, sizeof(struct HEADER), 1, input);
if (Header.Type != 0x4D42) {
printf("The specified input file was not a bitmap. Please try again.");
fclose(input);
return 1;
}
// getInfoHeader(input);
fread(&InfoHeader, sizeof(struct INFOHEADER), 1, input);
fseek(input, Header.Offset, SEEK_SET);
struct PIXEL arr[InfoHeader.Width][InfoHeader.Height];
printf("%d %d\n", InfoHeader.Width, InfoHeader.Height);
for (i = 0; i < InfoHeader.Width; i++) {
for (j = 0; j < InfoHeader.Height; j++) {
getPixel(input, arr[i] + j);
printf("%d %d %d\n", arr[i][j].Red, arr[i][j].Green, arr[i][j].Blue);
}
}
fclose(input);
}
}
也許這是一個填充問題,你需要'#pragma pack'結構INFOHEADER'。兩個「短」成員跳入我的眼睛。 「HEADER.Size」的值是否正確? – alk
這個程序似乎並沒有使用'width'和'height'被讀取 –
所以我假設你在調試器中看着它們,對吧? –