gpt4 book ai didi

c - bmp 图像到 c 中的矩阵(二维数组)

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:33 25 4
gpt4 key购买 nike

我需要使用 C 语言将 bmp(RGB 24 位)图像放入二维数组中。我写了一些函数,但这些函数只适用于方形图像。我创建了这个结构来存储像素:

typedef struct{
int red;
int green;
int blue;
}pixel;

我还创建了两个 int 外部值 Y 和 X 来存储图像的高度和宽度。这是代码(我省略了 setWidthHeight 和 CreateNewImage 函数,因为我确定它们有效)

int X, Y;

int bitmapin(FILE* fp,/* int height, int width, */ pixel** img1){
long n;
int t;
fseek(fp, 10, SEEK_SET);
fread(&t, 1, 4, fp); //reads the offset and puts it in t
fseek(fp, t, SEEK_SET);
int i, p, e;
e=4-((X*3)%4);
if (e==4) {
e=0;
}
for (i=Y-1; i>=0; i-- ) {
for (p=0; p<X; p++) {
n=fread(&img1[i][p].blue, 1, 1, fp);
if (n!=1) {
return 29;
}
n=fread(&img1[i][p].green, 1, 1, fp);
if (n!=1) {
return 30;
}
n=fread(&img1[i][p].red, 1, 1, fp);
if (n!=1) {
return 31;
}
}
fseek(fp, e, SEEK_CUR);
}
return 0;
}

pixel** make2Dpixelarray(/*int y, int x*/){
pixel** theArray;
theArray=(pixel**) malloc(X*sizeof(pixel*));
for (int i=0; i<X; i++) {
theArray[i]=(pixel*) malloc(Y*sizeof(pixel));
}
return theArray;
}



int main(int argc, const char * argv[]) {
FILE* fp;
fp=fopen("/Users/admin/desktop/Immagine5.bmp", "r");
if (fp==NULL) {
return 20;
}
setWidthHeight(fp); //Puts X=width and Y=height, it works
pixel** img1=make2Dpixelarray(); //Creates 2D pixel array and get the memory for it
bitmapin(fp, img1); //this function should put the values of RGB pixel into the matrix
CreateNewImage(fp, img1); //This function creates a new image.
return 0;
}

当图像是正方形时没有问题,但是当:

  • height>width:当我尝试读取 bitmapin() 中的第一个像素时出现错误“BAD_ACCESS...”
  • width>height:第一行像素即可。但左侧是右侧的一种副本,蓝色更多,绿色更少。

有人可以帮我解决这个问题吗?

最佳答案

当您将值读入数组时,您已经交换了 x 和 y。我认为。这不像我已经测试过这个或任何东西。太懒了。

for (i=Y-1; i>=0; i-- ) {
for (p=0; p<X; p++) {
n=fread(&img1[i][p].blue

i 遍历 Yp 遍历 X

当你 malloc 它时,你为 img[x][y] 设置了它

theArray=(pixel**) malloc(X*sizeof(pixel*));
for (int i=0; i<X; i++) {
theArray[i]=(pixel*) malloc(Y*sizeof(pixel));

一般建议:远离全局变量,为此我将按照您注释掉的方式传入变量。命名你的变量比 te 更好。您的返回值 29、30、31 是什么?尝试使用名称的枚举或#defines。 (然后你就忽略返回值)

这个错误不明显的最大原因可能是命名方案。我和p?来吧,传入 sizeX 和 sizeY,并将 x 和 y 作为您的工作变量。如果上下文不是 bitmapin(),变量甚至应该是 bitmapSizeX。命名很重要哟。

关于c - bmp 图像到 c 中的矩阵(二维数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31273502/

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