gpt4 book ai didi

c - 存储 BMP 文件的像素值

转载 作者:行者123 更新时间:2023-11-30 17:35:45 24 4
gpt4 key购买 nike

我试图将 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;
}

最佳答案

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

此外,printf 中的 %d 需要一个 int。您应该将 unsigned chars 转换为 int ,否则可能会崩溃。

关于c - 存储 BMP 文件的像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22928776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com