2012-02-19 39 views
0

我有很多問題試圖加載圖像文件(PIXELIMAGEFORMAT)。代碼不會讓過去比較神奇的頭值PIXELIMAGEFORMAT(沒有字符串結束字符)加載自定義圖像格式C/C++二進制

我的圖像格式是:

Bytes 0-15: PIXELIMAGEFORMAT (The Magic Header Value) 
Bytes 16-17: Width   (Formatted as 0000 xxxx xxxx xxxx) 
Bytes 18-19: Height   (Formatted as 0000 xxxx xxxx xxxx) 
Bytes 20-23: Bits Per Pixel (Formatted as 1000 1000 1000 1000) 
Bytes 24-31: NULL    (All 0's) 
Bytes 32-END: 32-Bit RGBA  (8 Bit Red, 8 Bit Green, 8 Bit Blue, 8 Bit Alpha) 

我的圖片加載代碼是:

char* vimg_LoadPIXELIMAGE(char* filePath) { 
    FILE* file; 
    file = fopen(filePath, "rb"); 
    if (file == NULL) return "a"; 

    char* header = (char*)malloc(32); 
    fread(header, sizeof(char), 32, file); 
    char* magicHeader = (char*)malloc(16); 
    const char magic[] = { 
    'P', 'I', 'X', 'E', 'L', 
    'I', 'M', 'A', 'G', 'E', 
    'F', 'O', 'R', 'M', 'A', 'T' 
    }; 
    strncpy(magicHeader, header, 16); 

    if (magicHeader != magic) return "b"; 

    unsigned short width; 
    unsigned short height; 

    memcpy(&width, header + 16, 2); 
    memcpy(&height, header + 18, 2); 

    unsigned int fileSize = width * height; 

    char* fullbuffer = (char*)malloc(fileSize+32); 
    char* buffer = (char*)malloc(fileSize); 
    fread(fullbuffer, 1, fileSize + 32, file); 
    memcpy(buffer, fullbuffer + 32, fileSize); 

    return buffer; 
} 

我的主功能是:

void main(int argc, char* argv) { 
    char* imgSRC; 
    imgSRC = vimg_LoadPIXELIMAGE("img.pfi"); 
    if (imgSRC == "a") 
    printf("File Is Null!\n"); 
    else if (imgSRC == "b") 
    printf("File Is Not a PIXELIMAGE!\n"); 
    else if (imgSRC == NULL) 
    printf("SEVERE ERROR!!!\n"); 
    else 
    printf(imgSRC); 
    system("pause"); 
} 

目前它是什麼應該 do打印出每個二進制像素的char值。

如果你願意,我也可以發佈我目前的圖片文件。

謝謝!

  • 阿德里安·科利亞

回答

1

你比較緩衝區的地址,而不是緩衝自己,你應該使用memcmp

if (memcmp(magicHeader, magic, 16) != 0) return "b"; 

這不是答案,而是也應該考慮:

你比較地址whi樂你應該比較值:

if (*imgSRC == 'a') 

而且,由於NULL可以返回,我會改變的檢查順序:

if (imgSRC == NULL) 
    printf("SEVERE ERROR!!!\n"); 
else if (*imgSRC == 'a') 
    printf("File Is Null!\n"); 
else if (*imgSRC == 'a') 
    printf("File Is Not a PIXELIMAGE!\n"); 
else 
    printf(imgSRC); 
+0

這是行不通的,因爲'* imgSRC'是內存位置。 'imgSRC'是一個char數組。無論如何,這不是錯誤的地方。當比較'magicHeader'和'magic'時出現錯誤,這兩個* DO *具有相同的值... – 2012-02-19 06:02:19

+0

另外..NULL不是專門返回的...它是作爲防止嘗試打印空值。每次運行代碼時,它都會打印「文件不是PIXELIMAGE!」串。 – 2012-02-19 06:04:34

+0

@AdrianCollado - 見編輯 – MByD 2012-02-19 06:10:47