0
I’m trying a problem with a code I did that should display the bytes referring to the RGB color values of each pixel of an image in bmp format (bitmap).
I know that in the windows api it is possible to work with bitmaps in a more practical way, but as I intend that the final code is portable in terms of operating system, I created the structs and I am reading only with 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 of these pixels are:
(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: https://prnt.sc/gnygch
And my way out 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 bottom 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?
The link you posted is not one bitmap
– user5299
I took a print because I tried upar, but it was converted to png and it was very small. I zoomed in and took a print.
– Wesley Alves
The problem is that there is no way to test your program, since you do not have the original bitmap
– user5299