Created
May 11, 2011 00:14
-
-
Save samuraisam/965661 to your computer and use it in GitHub Desktop.
Intelligently resize an image in python
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
from collections import namedtuple | |
from magickwand.image import Image | |
Size = namedtuple('Size', ['width','height']) | |
Point = namedtuple('Point', ['x','y']) | |
Rect = namedtuple('Rect', ['origin', 'size']) | |
class ResizeMethods: | |
fit = min | |
fill = max | |
def resize(size, filelike, method=ResizeMethods.fit): | |
""" | |
Returns an `magickwand.image.Image` object that is resized and/or cropped | |
to meet the requirements specified. available resize methods: | |
ResizeMethods.fit => image will fit within the bounds specified | |
ResizeMethods.fill => image will fill the bounds specified, cropping if necessary | |
`size` `Size` tuple - how big do you want the resulting image | |
`filelike` a file-like object (anything that provides a .read()) method | |
`method` function to determine in what way the scale should be determined | |
returns `magickwand.image.Image` object representing the image. have fun | |
""" | |
img = Image(filelike) | |
orig_size = Size(*img.size) | |
width_ratio = float(size.width) / float(orig_size.width) | |
height_ratio = float(size.height) / float(orig_size.height) | |
scale = method(width_ratio, height_ratio) | |
new_size = Size(int(float(orig_size.width) * scale), | |
int(float(orig_size.height) * scale)) | |
img.size = new_size | |
if method == ResizeMethods.fill: | |
crop_rect = Rect(Point(0, 0), Size(int(size.width), int(size.height))) | |
if new_size.width > crop_rect.size.width \ | |
or new_size.height > crop_rect.size.height: | |
crop_rect = Rect(Point(int((new_size.width - size.width) / 2.0), | |
int((new_size.height - size.height) / 2.0)), | |
crop_rect.size) # centerfy the cropping | |
img.crop(crop_rect.size, crop_rect.origin) | |
return img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment