gpt4 book ai didi

Python3 - 解析jpeg维度信息

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:05 26 4
gpt4 key购买 nike

我正在尝试编写一个 python 函数来解析 jpeg 文件的宽度和高度。我目前的代码看起来像这样

import struct

image = open('images/image.jpg','rb')
image.seek(199)
#reverse hex to deal with endianness...
hex = image.read(2)[::-1]+image.read(2)[::-1]
print(struct.unpack('HH',hex))
image.close()

虽然这有几个问题,首先我需要查看文件以确定从哪里读取(在 ff c0 00 11 08 之后),其次我需要避免从嵌入式缩略图中获取数据。有什么建议吗?

最佳答案

由于对字节和字符串的更改,我无法获得任何适用于 Python3 的解决方案。在 Acorn 的解决方案的基础上,我想出了这个,它在 Python3 中对我有用:

import struct
import io

height = -1
width = -1

dafile = open('test.jpg', 'rb')
jpeg = io.BytesIO(dafile.read())
try:

type_check = jpeg.read(2)
if type_check != b'\xff\xd8':
print("Not a JPG")
else:
byte = jpeg.read(1)

while byte != b"":

while byte != b'\xff': byte = jpeg.read(1)
while byte == b'\xff': byte = jpeg.read(1)

if (byte >= b'\xC0' and byte <= b'\xC3'):
jpeg.read(3)
h, w = struct.unpack('>HH', jpeg.read(4))
break
else:
jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)

byte = jpeg.read(1)

width = int(w)
height = int(h)

print("Width: %s, Height: %s" % (width, height))
finally:
jpeg.close()

关于Python3 - 解析jpeg维度信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5851607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com