簡體   English   中英

bmp圖像到c中的矩陣(二維數組)

[英]bmp image to matrix (2d array) in c

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

當圖像為正方形時,只有在以下情況時才沒有問題:

  • 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穿過Y並且p穿過X

分配時,將其設置為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。 命名很重要喲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM