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

标签 c arrays image bitmap bmp

我需要使用 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/

相关文章:

arrays - Swift 错误无法将类型 '[String.Element]'(又名 'Array<Character>')的值转换为预期的参数类型 '[String]'

php - 从 MySQL 查询构建数组

javascript - 将哈希中的键存储在另一个数组中

swift - 我如何在 webkit 中显示图像?

html - 将图像推到页面容器上

ios - 如何在Firebase中使用writeToFile来处理超出最大大小的情况?

C - 在没有头文件的情况下在多个文件中构造

c - 为什么此循环在C中的链接列表中不多次迭代?

c - malloc 结构指针数组与结构数组

c - 使用 GLFW 和 XCode : won't compile 时出现问题