2013-11-25 40 views
1

如何將單色bmp圖像文件(在我的情況下是16 * 16像素)轉換爲二進制格式?該代碼讀取位圖信息。我必須將像素信息存儲到一個數組中&它沒有正確存儲。我有共同的代碼bmp在C中的圖像數據

#pragma pack(push, 1) 

typedef struct BitMap 
    { 
short Signature; 
long Reserved1; 
long Reserved2; 
long DataOffSet; 
long Size; 
long Width; 
long Height; 
short Planes; 
short BitsPerPixel; 
long Compression; 
long SizeImage; 
long XPixelsPreMeter; 
long YPixelsPreMeter; 
long ColorsUsed; 
long ColorsImportant; 
long data[16]; 
}BitMap; 
#pragma pack(pop) 

讀取圖片文件:

struct BitMap source_info; 
struct Pix source_pix; 

FILE *fp; 
FILE *Dfp; 
Dfp=fopen("filename.bin","wb") 

if(!(fp=fopen("filename.bmp","rb"))) 
{ 
    printf(" can not open file"); 
    exit(-1); 
} 

fread(&source_info, sizeof(source_info),1,fp); 
printf("%d\n",source_info.DataOffSet); 
printf("%d\n",source_info.Width*source_info.Height); 
for(i=0;i<16;i++) 
fprintf(Dfp,"%d\t",source_info.data[i]); 

觀測的輸出使用十六進制編輯器是 hex output of monochrome bmp image

突出顯示的數據我想存儲在數據陣列,這樣我可以使用它進一步在代碼中。

但是在filename.bin輸出

0 16777215 63 63 63 95 95 95 
31 31  31 31 31 31 31 31 

我是新來這個領域。有人能幫我解決我出錯的地方嗎?

+0

首先,它可能是更容易,如果你打印的十六進制數,而不是比較值。 –

+1

@JoachimPileborg是的。實際上,如果OP嘗試使用十六進制數字沒有問題 - 它們只是相同的。 – starrify

+0

十六進制輸出是 0x00 0xffffff 0x3f 0x3f 0x3f 0x5f 0x5f 0x5f 0x1f 0x1f 0x1f 0x1f 0x1f 0x1f 0x1f 0x1f你能解釋輸出得到存儲?我無法獲得相同的輸出 – user2967899

回答

4

數據實際上沒有問題。
問題是您使用錯誤的方式來打印它們。

嘗試更換您的代碼:

printf("%d\n",source_info.DataOffSet); 
printf("%d\n",source_info.Width*source_info.Height); 
for(i=0;i<16;i++) 
    fprintf(Dfp,"%d\t",source_info.data[i]); 

與此:

printf("%x\n",source_info.DataOffSet); 
printf("%x\n",source_info.Width*source_info.Height); 
for(i=0;i<16;i++) 
    fprintf(Dfp,"%x\t",source_info.data[i]); 

至於%d是簽署小數,而%x是十六進制數。見The conversion specifier一節the manual page of printf

編輯:

正如你所發佈的新問題在意見:

在十六進制輸出爲0x00 0XFFFFFF 0x3F的0x3F的0x3F的0x5F的0x5F的0x5F的爲0x1F 0x1f 0x1f 0x1f 0x1f 0x1f 0x1f 0x1f你能解釋如何輸出存儲?我無法得到相同的輸出 - user2967899 7分鐘前

這裏是我編輯的答案。

假設:你的工作平臺是一樣正常,在其short大小爲2個字節和long這4
struct BitMap定義,我們知道現場data在它的0x36偏移。圖像的對比,我們知道數據應爲(十六進制):

data[0]: 0000 0000 
data[1]: ffff ff00 
...... 

那麼你得到的結果似乎很奇怪,因爲是0x00ffffffff,而不是0xffffff00。但是,這是正確的。首先請閱讀這個wiki頁面:http://en.wikipedia.org/wiki/Endianness
由於十六進制編輯器以字節的實際順序表示數據,並且我假設您正在使用一個小端機器(大多數PC機這個星球),這個順序被顛倒只是你的數據的真正秩序的long

/* data in C */ 
unsigned long x = 305419896; /* 305419896 == 0x12345678 */ 

/* arithmetically the four bytes in x: */ 
/* 0x12 0x34 0x56 0x78 */ 

/* the real order to be observed in a hex-editor due to endianess: */ 
/* 0x78 0x56 0x34 0x12 */ 

/* so this holds true in C: */ 
unsigned char *a = &x; 
assert(a[0] == 0x78); 
assert(a[1] == 0x56); 
assert(a[2] == 0x34); 
assert(a[3] == 0x12); 
+0

非常感謝。問題解決了 :) – user2967899