imghdr是python標準庫中非常短小的一個模塊,只有一個功能,就是識別影像的型別,而通過查看imghdr中的成員,則可看出這個包所能鑒別的影像型別,
>>> dir(imghdr)
[#內置引數就省略不寫了,,,
'test', 'test_bmp', 'test_exr', 'test_gif', 'test_jpeg', 'test_pbm', 'test_pgm', 'test_png', 'test_ppm', 'test_rast', 'test_rgb', 'test_tiff', 'test_webp', 'test_xbm', 'testall', 'tests', 'what']
其中真正有些實用頻率的函式也只有一個what,
>>> imghdr.what('cuda.png')
'png'
按理說這么簡單的模塊是沒有什么講解價值的,但這個模塊是完全用python寫的,換句話說,查看其原始碼,就能知道這些影像的檔案頭,
例如其鑒別gif的方法為
def test_gif(h, f):
"""GIF ('87 and '89 variants)"""
if h[:6] in (b'GIF87a', b'GIF89a'):
return 'gif'
也就是說,gif檔案的前六位必然為GIF87a或者GIF89a,改為十六進制則為47 49 46 38 37 61,由此可知這些影像格式的鑒別方法,在下表中h為16進制的影像資料
what值 | 影像格式 | 鑒別方法 |
|---|---|---|
| ‘jpeg’ | JFIF格式 Exif格式 | h[6:10]=b'JFIF'h[6:10]=b'Exif' |
| ‘png’ | 便攜式網路影像 | h[:8]=b'\211PNG\r\n\032\n' |
| ‘gif’ | GIF87a檔案 89a檔案 | h[:6]=b'GIF87a'h[:6]=b'GIF89a' |
| ‘bmp’ | BMP檔案 | h[:2]=b'BM' |
| ‘tiff’ | TIFF 檔案 | h[:2]=b'MM'或h[:2]=b'II' |
| ‘rgb’ | SGI影像庫檔案 | h[:2]=b'\001\332' |
| ‘webp’ | WebP 檔案 | h[:4]='RIFF'且h[8:12]=b'WEBP' |
| ‘rast’ | Sun 光柵檔案 | h[:4]=b'\x59\xA6\x6A\x95' |
| ‘exr’ | OpenEXR檔案 | h[:4]=b'v/1\x01' |
| ‘xbm’ | X 位圖檔案 | h[:8]=b'#define ' |
此外,pbm, pgm, ppm這三種格式均以b'P'開頭,第三位為b' \t\n\r'中的一種,區別在于第二位
| 格式 | h[1] | |
|---|---|---|
| ‘pbm’ | 便攜式位圖檔案 | h[1] in '14' |
| ‘pgm’ | 便攜式灰度圖檔案 | h[1] in b'25' |
| ‘ppm’ | 便攜式像素表檔案 | h[1] in b'36' |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/377239.html
標籤:其他
上一篇:vs2015配置vcpkg
