I'm trying to work on a bmp file. For a start i tried to read a header and a data from a bmp file and to write it to a new file:
#pragma pack(push,1)
/* Windows 3.x bitmap file header */
typedef struct {
char filetype[2]; /* magic - always 'B' 'M' */
unsigned int filesize;
short reserved1;
short reserved2;
unsigned int dataoffset; /* offset in bytes to actual bitmap data */
} file_header;
/* Windows 3.x bitmap full header, including file header */
typedef struct {
file_header 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;
} bitmap_header;
#pragma pack(pop)
int foo(char* input, char *output) {
//variable dec:
FILE *fp,*out;
bitmap_header* hp;
int n;
char *data;
//Open input file:
fp = fopen(input, "r");
if(fp==NULL){
//cleanup
}
//Read the input file headers:
hp=(bitmap_header*)malloc(sizeof(bitmap_header));
if(hp==NULL)
return 3;
n=fread(hp, sizeof(bitmap_header), 1, fp);
if(n<1){
//cleanup
}
//Read the data of the image:
data = (char*)malloc(sizeof(char)*hp->bitmapsize);
if(data==NULL){
//cleanup
}
fseek(fp,sizeof(char)*hp->fileheader.dataoffset,SEEK_SET);
n=fread(data,sizeof(char),hp->bitmapsize, fp);
if(n<1){
//cleanup
}
//Open output file:
out = fopen(output, "w");
if(out==NULL){
//cleanup
}
n=fwrite(hp,sizeof(char),sizeof(bitmap_header),out);
if(n<1){
//cleanup
}
fseek(out,sizeof(char)*hp->fileheader.dataoffset,SEEK_SET);
n=fwrite(data,sizeof(char),hp->bitmapsize,out);
if(n<1){
//cleanup
}
fclose(fp);
fclose(out);
free(hp);
free(data);
return 0;
}
This is the input file:
and this is the output:
They are the same size and seems that have the same headers. What can be wrong? Thanks.
You can open BMP files on either PC or Mac with external software, such as Adobe Creative Cloud. If you use a PC or Mac, start by opening the folder with the BMP file you want to use. Right-click on the file name and then hover over the Open With option.
The BMP file format, also known as bitmap image file, device independent bitmap (DIB) file format and bitmap, is a raster graphics image file format used to store bitmap digital images, independently of the display device (such as a graphics adapter), especially on Microsoft Windows and OS/2 operating systems.
Since we have that loaded, we check if the file is a BMP file. Allocate pixel memory, then jump to where the pixel data starts and read. // First allocate pixel memory pixels = new Uint8[bmpInfo->biSizeImage]; // Go to where image data starts, then read in image data file.
I'm going to guess that you should be opening your files in binary mode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With