Python Struct讀取bmp圖片資訊
阿新 • • 發佈:2018-12-27
struct的pack函式可以把任意資料型別變成bytes:
>>> import struct
>>> struct.pack('>I',10240099)
b'\x00\[email protected]'
pack的第一個引數是處理指令,'>I'的意思是: >表示位元組順序是big-endian,也就是網路序,I表示4位元組無符號整數。
struct的unpack函式把bytes變成相應的資料型別:
>>> import struct >>> struct.unpack('>IH',b'\xf0\xf0\xf0\xf0\x80\x80') (4042322160, 32896)
'>IH'的意思是:後面的bytes依次變為I:4位元組無符號整數和H:2位元組無符號整數
Windows的點陣圖檔案(.bmp)是一種採用小端方式儲存資料,檔案頭的結構順序如下:
兩個位元組:'BM'表示Windows點陣圖,'BA'表示OS/2點陣圖
一個4位元組整數:點陣圖大小
一個4位元組整數:保留位,始終為0
一個4位元組整數:實際影象的偏移量
一個4位元組整數:Header的位元組數
一個4位元組整數:影象寬度
一個4位元組整數:影象高度
一個2位元組整數:始終為1
一個2位元組整數:顏色數
所以,組合起來用unpack讀取:
>>> struct.unpack('<ccIIIIIIHH', s) (b'B', b'M', 691256, 0, 54, 40, 640, 360, 1, 24)
b'B、b'M說明是Windows點陣圖,點陣圖大小為640*360,顏色數為24
舉例讀取檔案
#!usr/bin/env python3 # -*- coding:utf-8 -*- import base64,struct with open('test001.bmp','rb') as f: s=f.read(30) print(s) def bmp_info(): unpackbuf=struct.unpack('<ccIIIIIIHH',s) if (unpackbuf[0]!=b'B' or unpackbuf[1]!=b'M'): return None else: return {'width':unpackbuf[6],'height':unpackbuf[7],'color':unpackbuf[9]} bi=bmp_info() print(bi['width'],bi['height'],bi['color'])
PS F:\Work> python bmpinfo.py
b'BM\xe6\x15\x02\x00\x00\x00\x00\x006\x04\x00\x00(\x00\x00\x00\xc2\x01\x00\x00,\x01\x00\x00\x01\x00\x08\x00'
450 300 8