存储BMP文件的像素值

时间:2014-04-08 06:04:37

标签: c struct pixels bmp

我试图将BMP文件的像素值存储在2D动态分配的结构数组中,但它不断给出分段错误。这就是我到目前为止所拥有的:

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

typedef struct PIXEL{
        unsigned char Red, Green, Blue;
}*pixel;

int main (int argc, char *argv[])
{
        //variable declarations and open the file
        FILE* fin = fopen(argv[1], "rb");
        if (fin == NULL){
                printf("Error opening file.\n");
                exit(0);
        }
        unsigned char info[54];
        int width, height, i, j;

        fread(info, sizeof(unsigned char), 54, fin);    //read the header
        width = *(int*)&info[18];
        height = *(int*)&info[22];

        pixel **image = (pixel **) malloc(sizeof(pixel *) * width); //reserve enough space for RGB for each pixel
        for (i = 0; i < width; i++){
                image[i] = (pixel *) malloc(sizeof(pixel) * height);
        }

        for (i = 0; i < width; i++){
                for (j = 0; j < height; j++){
                        image[i][j]->Blue = getc(fin);  //put the blue value of the pixel
                        image[i][j]->Green = getc(fin); //green value
                        image[i][j]->Red = getc(fin);   //red value
                        printf("Pixel %d: [%d, %d, %d]\n", (i+1)*(j+1), image[i][j]->Blue, image[i][j]->Green, image[i][j]->Blue);
                }
        }

        fclose(fin);
        return 0;
}

1 个答案:

答案 0 :(得分:0)

您没有从标题中检查有效的宽度和高度值。如果由于任何原因它们很大(例如,如果文件读取失败),这将会崩溃。

此外,printf中的%d需要一个int。您应该将未签名的字符转换为int,否则它可能会崩溃。