gpt4 book ai didi

python - 如何在 python 3 中获得 jpeg 分辨率,而不需要任何外来库?

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:38 25 4
gpt4 key购买 nike

我是Python编程的菜鸟。我找不到答案,如何在 python 版本 3 中获得 jpeg 分辨率,而不使用任何外部库。我已经尝试过这段代码,但结果是不可预测的。我不明白为什么..

def jpeg_res(filename):

# open image for reading in binary mode
with open(filename,'rb') as img_file:

# height of image (in 2 bytes) is at 164th position
img_file.seek(163)

# read the 2 bytes
a = img_file.read(2)

# calculate height
height = (a[0] << 8) + a[1]

# next 2 bytes is width
a = img_file.read(2)

# calculate width
width = (a[0] << 8) + a[1]

print("The resolution of the image is",width,"x",height)

jpeg_res("img1.jpg")

我正在使用在 MS Windows 7(64 位)上运行的 python 版本 3.5

最佳答案

这段代码对我有用:

def get_image_size(fname):
'''Determine the image type of fhandle and return its size.
from draco'''
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
return
if imghdr.what(fname) == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
return
width, height = struct.unpack('>ii', head[16:24])
elif imghdr.what(fname) == 'gif':
width, height = struct.unpack('<HH', head[6:10])
elif imghdr.what(fname) == 'jpeg':
try:
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
except Exception: #IGNORE:W0703
return
else:
return
return str(width) + "x" + str(height)

GitHub 上的完整代码。 https://goo.gl/w6U8Y7

关于python - 如何在 python 3 中获得 jpeg 分辨率,而不需要任何外来库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33084053/

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