Skip to content

Instantly share code, notes, and snippets.

@truemped
Created April 10, 2012 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save truemped/2351607 to your computer and use it in GitHub Desktop.
Save truemped/2351607 to your computer and use it in GitHub Desktop.
Thumbnail generation keeping the aspect ratio of the target width and height
# vim: set fileencoding: utf-8 :
#
import os
try:
from PIL import Image
except ImportError:
import Image
try:
from cStringIO import StringIO as StringIO
except ImportError:
from StringIO import StringIO
def get_thumbnail(img_filename, img_data, new_width, new_height, crop=True):
"""
Create a thumbnailed version of the image.
`img_filename` is used for detecting the image format using the filename
extension. `img_data` is a `str` containing the bytes from the file.
`size_x` and `size_y` denote the desired image format.
If `crop`, then crop the image before calculating the thumbnail. Depending
on the target size and the resulting ratio parts of the image will be
removed either on the top/bottom or left/right parts.
"""
img = Image.open(StringIO(img_data))
ratio = float(new_height)/new_width
if crop:
# crop the image either on right and left or on top and bottom
(width, height) = img.size
ratio_orig = float(height)/width
left, top, right, bottom = 0, 0, width, height
if ratio_orig > ratio:
# crop from the top and bottom of the original image
top = int((height - (width * ratio)) / 2)
bottom = height - top
elif ratio_orig < ratio:
# crop from the left and right of the original image
left = int((width - (height / ratio)) / 2)
right = width - left
img = img.crop((left, top, right, bottom))
img.thumbnail((new_width, new_height), Image.ANTIALIAS)
thumbnail = StringIO()
ext = os.path.splitext(img_filename)[1][1:].upper()
img.save(thumbnail, ext.replace('JPG', 'JPEG'))
return thumbnail.getvalue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment