Reading BGR colors from a bitmap in C

I tried to get RGB values ​​from a 24 bit BMP file. The image I use is a tiny image, everything is red, so all the BGR settings for the pixels should be B:0 G:0 R:255. I'm doing it:

int main(int argc, char **argv)
{
    principal();
    return 0;
}

typedef struct {
    unsigned char blue;
    unsigned char green;
    unsigned char red;
} rgb;

typedef struct {
    int ancho, alto;
    rgb *pixeles[MAX_COORD][MAX_COORD];
} tBitmapData;

void principal()
{

    FILE *fichero;
    tBitmapData *bmpdata = (tBitmapData *) malloc(sizeof(tBitmapData));
    rgb *pixel;
    int i, j, num_bytes;
    unsigned char *buffer_imag;
    char nombre[] = "imagen.bmp";
    fichero = fopen(nombre, "r");
    if (fichero == NULL)
            puts("No encontrado\n");
    else {
            fseek(fichero, 18, SEEK_SET);
            fread(&(bmpdata->ancho), sizeof((bmpdata->ancho)), 4, fichero);
            printf("Ancho: %d\n", bmpdata->ancho);
            fseek(fichero, 22, SEEK_SET);
            fread(&(bmpdata->alto), sizeof((bmpdata->alto)), 4, fichero);
            printf("Alto: %d\n", bmpdata->alto);
    }

    num_bytes = (bmpdata->alto * bmpdata->ancho * 3);
    fseek(fichero, 54, SEEK_SET);
    for (j = 0; j < bmpdata->alto; j++) {
            printf("R   G   B Fila %d\n", j + 1);
            for (i = 0; i < bmpdata->ancho; i++) {
                    pixel =
                        (rgb *) malloc(sizeof(rgb) * bmpdata->alto *
                                       bmpdata->ancho * 3);
                    fread(pixel, 1, sizeof(rgb), fichero);
                    printf("Pixel %d: B: %3d G: %d R: %d \n", i + 1,
                           pixel->blue, pixel->green, pixel->red);
            }
    }
    fclose(fichero);
}

The problem is that when I print them, the first pixels are fine B:0 G:0 R:255, but then they start to change to B:0 G:255 R:0, and then to B:255 G:0 R:0. If the width is 10 pixels, a change occurs every 10 pixels.

+3
source share
2 answers

In BMP format, each row of pixel data can be padded to round to a few bytes.

10 24- , 30 , 2 . .

+5

, fread(3) :

        fread(&(bmpdata->ancho), sizeof((bmpdata->ancho)), 4, fichero);

4*sizeof((bmpdata->ancho)) int. , sizeof((bmpdata->ancho)) 4, , . 4 1 - .

num_bytes; . , .:)

, :

                pixel =
                    (rgb *) malloc(sizeof(rgb) * bmpdata->alto *
                                   bmpdata->ancho * 3);

3 , , rgb, sizeof(rgb) . ( 4 , 32- 12 , ( char 4) , , 24 64- , , 8.)

, :

                fread(pixel, 1, sizeof(rgb), fichero);

C , , . GNU C __packed__, , bmp. , __packed__: , , , , , , . -, , , .

( , , ; CVE , , .)

+2

All Articles