Read color bytes (RGB) from a bitmap

0

I'm trying a problem with a code that I made that should display the bytes referring to the RGB color values of each pixel of an image in bmp (bitmap) format.

I know that in windows api you have to work with bitmaps in a more practical way, but since I want the final code to be portable in the operating system, I created the structs and I'm just reading the basics of C.

The code is this:

#include <stdio.h>
#include <stdlib.h>

unsigned char *readBMP(char *filename, int *size) {
    int width, height;
    unsigned char *data;
    unsigned char info[54];

    FILE *file = fopen(filename, "rb");
    if (file == NULL)
        return 0;

    fread(info, sizeof(unsigned char), 54, file); // read the 54-byte header

    // extract image height and width from header
    width = *(int *) &info[18];
    height = *(int *) &info[22];

    *size = 3 * width * height;
    data = (unsigned char *) malloc(*size * sizeof(unsigned char)); // allocate 3 bytes per pixel
    fread(data, sizeof(unsigned char), (size_t) *size, file); // read the rest of the data at once

    for (int i = 0; i < *size; i += 3) {
        unsigned char tmp = data[i];
        data[i] = data[i + 2];
        data[i + 2] = tmp;
    }

    fclose(file);
    return data;
}

int main() {
    int size = 0;
    char filename[] = "output.bmp";
    unsigned char *data = readBMP(filename, &size);

    for (int i = 0; i < size; i++) {
        printf("%d. %d\n", i + 1, (int) data[i]);
        if ((i + 1) % 3 == 0)
            printf("\n");
    }

    free(data);
    return 0;
}

The RGB code for these pixels is:

(0, 0, 0), (0, 0, 255),
(0, 255, 0), (0, 255, 255),
(255, 0, 0), (255, 0, 255);

The image I'm trying to "read" is a 2x3 pixel bitmap: link

And my output is:

1. 255
2. 0
3. 0

4. 255
5. 0
6. 255

7. 0
8. 0
9. 0

10. 255
11. 0
12. 255

13. 0
14. 0
15. 255

16. 0
17. 0
18. 0

The first readings even coincide with the low pixels, but the others do not match the other pixels, at least not in the order they are arranged.

Can anyone see what I'm doing wrong?

    
asked by anonymous 21.09.2017 / 17:22

0 answers