Created
December 1, 2011 14:04
-
-
Save vstoykov/1416949 to your computer and use it in GitHub Desktop.
Function that make cropped thumbnail from given Image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def croppedthumbnail(image, width, height, method=None): | |
''' | |
Function that make a thumbnail with given size | |
but crop image to fit in aspect ratio | |
image must be a instance of PIL.Image | |
''' | |
dst_width = int(width) | |
dst_height = int(height) | |
src_width, src_height = image.size | |
src_ratio = float(src_width) / float(src_height) | |
dst_ratio = float(dst_width) / float(dst_height) | |
if dst_ratio < src_ratio: | |
crop_height = src_height | |
crop_width = crop_height * dst_ratio | |
x_offset = float(src_width - crop_width) / 2 | |
y_offset = 0 | |
else: | |
crop_width = src_width | |
crop_height = crop_width / dst_ratio | |
x_offset = 0 | |
y_offset = float(src_height - crop_height) / 3 | |
image = image.crop((int(x_offset), int(y_offset), int(x_offset+crop_width), int(y_offset+crop_height))) | |
image = image.resize((dst_width, dst_height), method) | |
return image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment