Click here to Skip to main content
15,566,522 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm writing the code for image read and write.But, I don't understand how to define image data types, image_t

What I have tried:

// read the image
BMP readBMP(string filename) {
    BMP image;
    int i;
    string fileName = filename;
    FILE *f = fopen(fileName.c_str(), "rb");
    fread(image.header, sizeof(unsigned char), 54, f); // read the 54-byte header

    // extract image height and width from header
    image.width = *(int *) &image.header[18];
    image.height = *(int *) &image.header[22];
    cout<<"inage width: "<< image.width <<", image height: "<< image.height <<endl;

    image.size = 3 * image.width * image.height;
    image.pixels = new unsigned char[image.size]; // allocate 3 bytes per pixel
    fread(image.pixels, sizeof(unsigned char), image.size, f); // read the rest of the data at once
    fclose(f);

    // bmp stors data in BGR format, so changing the BGR to RGB.
    for (i = 0; i < image.size; i += 3) {
        unsigned char tmp = image.pixels[i];
        image.pixels[i] = image.pixels[i + 2];
        image.pixels[i + 2] = tmp;
    }
    return image;
}

// write image
void writeBMP(string filename, BMP image) {
    string fileName = filename;
    FILE *out = fopen(fileName.c_str(), "wb");
    fwrite(image.header, sizeof(unsigned char), 54, out);
    int i;
    unsigned char tmp;
    for (i = 0; i < image.size; i += 3) {
        tmp = image.pixels[i];
        image.pixels[i] = image.pixels[i + 2];
        image.pixels[i + 2] = tmp;
    }
    fwrite(image.pixels, sizeof(unsigned char), image.size, out); // read the rest of the data at once
    fclose(out);
}
Posted
Updated 18-Jan-22 2:42am
v2

1 solution

Check the structures defined by Microsoft: BITMAPFILEHEADER (wingdi.h) - Win32 apps | Microsoft Docs[^].
 
Share this answer
 
Comments
Harshad patil 2022 18-Jan-22 8:01am    
How to apply in my code
Richard MacCutchan 18-Jan-22 8:12am    
Sorry, no idea. You need to explain your problem in proper detail. Please use the Improve question link above, and add complete details of what is not working.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900