我使用的是Python 2.5。使用Python中的标准类,我想确定文件的图像大小。
我听说过PIL (Python Image Library),但它需要安装才能工作。
如何在不使用任何外部库的情况下,仅使用Python2.5自己的模块来获取图像的大小?
注意:我想支持常见的图像格式,特别是JPG和PNG。
发布于 2013-12-05 00:21:22
这是一个Python3脚本,它返回一个元组,其中包含.png、.gif和.jpeg的图像高度和宽度,而不使用任何外部库(即上面提到的Kurt McKee )。把它移植到Python2应该相对容易些。
import struct
import imghdr
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 width, height
发布于 2012-02-29 21:25:25
库尔特的答案需要稍微修改一下才能为我工作。
首先,在ubuntu上:sudo apt-get install python-imaging
然后:
from PIL import Image
im=Image.open(filepath)
im.size # (width,height) tuple
有关更多信息,请查看handbook。
发布于 2014-02-04 22:43:17
这是一种无需第三方模块即可获取png文件大小的方法。来自http://coreygoldberg.blogspot.com/2013/01/python-verify-png-file-and-get-image.html
import struct
def get_image_info(data):
if is_png(data):
w, h = struct.unpack('>LL', data[16:24])
width = int(w)
height = int(h)
else:
raise Exception('not a png image')
return width, height
def is_png(data):
return (data[:8] == '\211PNG\r\n\032\n'and (data[12:16] == 'IHDR'))
if __name__ == '__main__':
with open('foo.png', 'rb') as f:
data = f.read()
print is_png(data)
print get_image_info(data)
当您运行此命令时,它将返回:
True
(x, y)
还有另一个也包含JPEG处理的例子:http://markasread.net/post/17551554979/get-image-size-info-using-pure-python-code
https://stackoverflow.com/questions/8032642
复制相似问题