python - How do I make PIL take into account the shortest side when creating a thumbnail? -
currently, function below...the image resized based on longest side.
basically image has larger height, height 200px. width just...whatever...
if image has larger width, width 200px, , height adjust accordingly.
how flip around!? want function take account shortest side.
am writing function incorrectly??
def create_thumbnail(f, width=200, height=none, pad = false): #resizes longest side!!! doesn't care shortest side #this function maintains aspect ratio. if height==none: height=width im = image.open(stringio(f)) imagex = int(im.size[0]) imagey = int(im.size[1]) if imagex < width or imagey < height: pass #return none if im.mode not in ('l', 'rgb', 'rgba'): im = im.convert('rgb') im.thumbnail((width, height), image.antialias) thumbnail_file = stringio() im.save(thumbnail_file, 'jpeg') thumbnail_file.seek(0) return thumbnail_file
use resize
instead of thumbnail
.
the point behind thumbnail
make easy scale image down fit within particular bounding box preserving aspect ratio. means if bounding box square, longer side of image determines scale used.
resize
gives more direct control -- specify size want.
actually, since want preserve aspect still use thumbnail, need fudge bounding box. before call thumbnail
, try doing this:
old_aspect = float(imagex)/float(imagey) new_aspect = float(width)/float(height) if old_aspect < new_aspect: height = int(width / old_aspect) else: width = int(height * old_aspect)
Comments
Post a Comment