一个基于“原始”CPP转换的Python解决方案 -
https://dev59.com/y3E85IYBdhLWcg3w_Itr#62245035。
def get_jpeg_resolution(image_bytes: bytes,
size: int = None) -> Optional[Tuple[int, int]]:
"""
function for getting resolution from binary
:param image_bytes: image binary
:param size: image_bytes len if value is None it'll calc inside
:return: (width, height) or None if not found
"""
size = len(image_bytes) if size is None else size
header_bytes = (0xff, 0xD8, 0xff, 0xe0)
if not (size > 11
and header_bytes == struct.unpack_from('>4B', image_bytes)):
return None
jfif_bytes = tuple(ord(s) for s in 'JFIF') + (0x0, )
if not (jfif_bytes == struct.unpack_from('5B', image_bytes, 6)):
return None
index = len(header_bytes)
block_length, = struct.unpack_from(">H", image_bytes, index)
index += block_length
while index < size:
if image_bytes[index] != 0xFF:
break
if image_bytes[index + 1] == 0xC0:
height, width = struct.unpack_from(">HH", image_bytes, index + 5)
return width, height
else:
index += 2
block_length, = struct.unpack(">H",
image_bytes[slice(index, index + 2)])
index += block_length
return None