I'm trying to open a .bmp image file and to read bitmap data to a buffer. but I'm not getting the excepted output. I'm new to C language and please assist me on this case.
this is my "main.c" file.
#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;
}
This is the output :
I can not print any data of the "bitmapData" buffer. This is the .bmp file which I used in the program.
Image size (1,229,878 bytes)
width 1280 pixels / height 960 pixels
I replaced the line,
printf("bitmapData: %s", bitmapData );
with
printf("bitmapData: "); fwrite(bitmapData, 1280*960, 1, stdout);