使用适当的库可能会更好,例如wand
or exiftool
,但是如果您想要轻量级的东西,这可能就足够了-但是我无法在您的图像上对其进行测试,因为您没有共享任何内容:
#!/usr/bin/env python3
import sys
import struct
# Read first 100 bytes
with open('a.bmp','rb') as f:
BMP = f.read(100)
if BMP[0:2] != b'BM':
sys.exit('ERROR: Incorrect BMP signature')
# Get BITMAPINFOHEADER size - https://en.wikipedia.org/wiki/BMP_file_format
BITMAPINFOHEADERSIZE = struct.unpack('<i',BMP[14:18])[0]
okSizes = [40, 52, 56, 108, 124]
if BITMAPINFOHEADERSIZE not in okSizes:
sys.exit(f'ERROR: BITMAPINFOHEADER size was {BITMAPINFOHEADERSIZE}, expected one of {okSizes}')
# Get bits per pixel
bpp = struct.unpack('<H',BMP[28:30])[0]
print(f'bbp: {bpp}')
我使用ImageMagick创建了一个示例 BMP,如下所示:
magick -size 32x32 xc:red -define bmp:subtype=RGB565 a.bmp
然后我运行我的脚本并得到bpp:16
匹配的exiftool
输出:
exiftool a.bmp
ExifTool Version Number : 12.00
File Name : a.bmp
Directory : .
File Size : 2.1 kB
File Modification Date/Time : 2021:02:24 12:01:51+00:00
File Access Date/Time : 2021:02:24 12:01:52+00:00
File Inode Change Date/Time : 2021:02:24 12:01:51+00:00
File Permissions : rw-r--r--
File Type : BMP
File Type Extension : bmp
MIME Type : image/bmp
BMP Version : Windows V5
Image Width : 32
Image Height : 32
Planes : 1
Bit Depth : 16 <--- HERE IT IS
Compression : Bitfields
Image Length : 2048
Pixels Per Meter X : 0
Pixels Per Meter Y : 0
Num Colors : Use BitDepth
Num Important Colors : All
Red Mask : 0x0000f800
Green Mask : 0x000007e0
Blue Mask : 0x0000001f
Alpha Mask : 0x00000000
Color Space : sRGB
Rendering Intent : Picture (LCS_GM_IMAGES)
Image Size : 32x32
Megapixels : 0.001
然后我创建了一个像这样的 24 位 BMP:
magick -size 32x32 xc:red a.bmp
以及我的 Python 和exiftool
报告 24 bpp。
关键词:Python。BMP,图像处理,获取深度,位深度,bpp。