我正在嘗試編寫程序以反轉圖像的顏色。我的問題是當我嘗試從我的BMP文件中的DIB標題讀取。在C內存中讀取和寫入BMP文件錯誤
當我嘗試獲取文件頭大小並使用fread(dib.fileheader,4,1,fp); 。我收到一個錯誤,指出「無法寫入內存」。我已附上它作進一步澄清。
這裏是我的代碼:
#include <stdio.h>
#include <string.h>
struct BMP {
char filetype[2]; // must be BM, must check if BM
unsigned int filesize;
short reserved1;
short reserved2;
unsigned int dataoffset;
};
struct DIB {
unsigned int fileheader;
unsigned int headersize;
int width;
int height;
short planes;
short bitsperpixel; /* we only support the value 24 here */
unsigned int compression; /* we do not support compression */
unsigned int bitmapsize;
int horizontalres;
int verticalres;
unsigned int numcolors;
unsigned int importantcolors
};
struct pixel {
int val;
char * def;
struct listitem * next;
};
void invertImage(char fileName[]){
struct BMP bmp;
struct DIB dib;
FILE *fp = fopen(fileName, "rb");
//FileType
fread(bmp.filetype, 1,2,fp);
printf("Value is %c\n", bmp.filetype[1]);
//Check if file format is BM
if(bmp.filetype[0] != 'B' && bmp.filetype[1] !='M'){
printf("Wrong format");
}
//Size of the file in bytes
fread(bmp.filesize, 4,1,fp);
printf("Value is %d\n", bmp.filesize);
//Go to dataoffset
fseek(fp,10,SEEK_CUR);
fread(bmp.dataoffset, 4,1,fp);
printf("Offset is %d\n", bmp.dataoffset);
fread(dib.fileheader, 4,1,fp);
printf("File header is %d bytes\n", dib.fileheader);
fclose(fp);
}
int main(int argc, char *argv[]){
printf("Program name %s\n", argv[0]);
if(strcmp(argv[1],"-invert") == 0) {
printf("Invert\n");
printf("File name is %s\n", argv[2]);
invertImage(argv[2]);
}
else {
printf("Greyscale\n");
//greyScaleImage();
}
return 0;
}
而且,這裏是輸出到我的計劃。
請**啓用所有警告編譯**。您應該將C編譯器的所有警告視爲**錯誤**。如果您無法解決警告,那麼您可以詢問有關情況。 –
還要注意你的代碼依賴於32位寬的'unsigned int'。 –
此外,對於[MCVE](mcve),請刪除圖像中的所有不必要的代碼,並且如果可能,請格式化代碼以使其很好地縮進。現在,一半的代碼行甚至在崩潰之前並未實際使用。 –