cmp中的bmp图像到矩阵(2d数组)

问题描述 投票:1回答:1

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

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

我还创建了两个int extern值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;
}

当图像是方形时,没有问题,但在以下情况时:

  • 高度>宽度:当我尝试读取bitmapin()中的第一个像素时,我收到错误“BAD_ACCESS ...”
  • width> height:第一行像素是OK。但是左侧是右侧的副本,有更多的蓝色和非常小的绿色。

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

c arrays image bitmap bmp
1个回答
1
投票

当您将值传入数组时,您已经交换了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。 (之后你只需忽略返回值)

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

© www.soinside.com 2019 - 2024. All rights reserved.