Using PIL to extract width and height of the image is not necessary. For that I'm using handy function that I got from draco http://draco.boskant.nl/:
Works for GIF, PNG and JPEG formats.
Also, maybe is useful to cache results of function to avoid accessing to file system frequently.
Another good idea from draco is the IMG tag rewriter which automatically adds image width and height to img tags. Can this be added to template system?
def _imageInfo(fhandle):
"""
Determine the image type of fhandle and return its size.
from draco
"""
head = fhandle.read(24)
if len(head) != 24:
return
if head[:4] == '\x89PNG':
# PNG
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
return
width, height = struct.unpack('>ii', head[16:24])
img_type = 'PNG'
elif head[:6] in ('GIF87a', 'GIF89a'):
# GIF
width, height = struct.unpack('<HH', head[6:10])
img_type = 'GIF'
elif head[:4] == '\xff\xd8\xff\xe0' and head[6:10] == 'JFIF':
# JPEG
img_type = '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 img_type, width, height
# imageSize