2012-02-19 43 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