[英]Can not Read Bitmap data of a (1280 x 960) .bmp image In C
我正在嘗試打開 .bmp 圖像文件並將位圖數據讀取到緩沖區。 但我沒有得到例外的輸出。 我是 C 語言的新手,請在這種情況下幫助我。
這是我的“main.c”文件。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint32_t DWORD; // DWORD = unsigned 32 bit value
typedef uint16_t WORD; // WORD = unsigned 16 bit value
#pragma pack(push, 1)
typedef struct {
WORD bfType; //specifies the file type
DWORD bfSize; //specifies the size in bytes of the bitmap file
WORD bfReserved1; //reserved; must be 0
WORD bfReserved2; //reserved; must be 0
DWORD offset; //specifies the offset in bytes from the bitmapfileheader to the bitmap bits
} BMP_FILE_HEADER;
#pragma pack(pop)
unsigned char *LoadBitmapFile(char *filename)
{
FILE *filePtr; //our file pointer
BMP_FILE_HEADER bitmapFileHeader; //our bitmap file header
unsigned char *bitmapImage; //store image data
size_t bytes_read;
//open file in read binary mode
filePtr = fopen(filename,"rb");
if (filePtr == NULL)
return NULL;
//read the bitmap file header
fread(&bitmapFileHeader,1,sizeof(BMP_FILE_HEADER),filePtr);
printf("Type : %d \n",bitmapFileHeader.bfType );
//verify that this is a .BMP file by checking bitmap id
if (bitmapFileHeader.bfType !=0x4D42)
{
printf("This is not a bitmap" );
fclose(filePtr);
return NULL;
}
//move file pointer to the beginning of bitmap data
fseek(filePtr,bitmapFileHeader.offset, SEEK_SET);
printf("Where is the file pointer = %ld \n", ftell(filePtr) );
//allocate enough memory for the bitmap image data
bitmapImage = (unsigned char*)malloc(1280*960);
//verify memory allocation
if (!bitmapImage)
{
printf("Memory Allocation failed" );
free(bitmapImage);
fclose(filePtr);
return NULL;
}
//read in the bitmap image data
bytes_read = fread(bitmapImage,1,1280*960 ,filePtr);
printf("Read Bytes : %zu\n",bytes_read );
//make sure bitmap image data was read
if (bitmapImage == NULL)
{
printf("data was not read" );
fclose(filePtr);
return NULL;
}
printf("bitmapImage: %s\n", bitmapImage );
printf("Header- size -> %i\n",bitmapFileHeader.bfSize );
printf("Header- OffSet -> %i\n",bitmapFileHeader.offset );
//close file and return bitmap image data
fclose(filePtr);
return bitmapImage;
}
int main(){
unsigned char *bitmapData;
bitmapData = LoadBitmapFile("img_06.bmp");
printf("bitmapData: %s", bitmapData );
return 0;
}
這是輸出:
我無法打印“bitmapData”緩沖區的任何數據。 這是我在程序中使用的 .bmp 文件。
圖像大小(1,229,878 字節)
寬1280像素/高960像素
I replaced the line,
printf("bitmapData: %s", bitmapData );
with
printf("bitmapData: "); fwrite(bitmapData, 1280*960, 1, stdout);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.