Avoid duplication of cropping code

`Fill` is just a resize followed by a crop, so we might as well make
use of the processors we already have.
This commit is contained in:
Matthew Tretter 2012-02-11 14:25:06 -05:00
parent 16110a0f1c
commit b4b64a4863

View file

@ -1,37 +1,26 @@
from imagekit.lib import Image
from .crop import SmartCrop as _SmartCrop
from . import crop
import warnings
class Resize(object):
pass
class Fill(object):
"""
Resizes an image , cropping it to the exact specified width and height.
"""
TOP_LEFT = 'tl'
TOP = 't'
TOP_RIGHT = 'tr'
BOTTOM_LEFT = 'bl'
BOTTOM = 'b'
BOTTOM_RIGHT = 'br'
CENTER = 'c'
LEFT = 'l'
RIGHT = 'r'
_ANCHOR_PTS = {
TOP_LEFT: (0, 0),
TOP: (0.5, 0),
TOP_RIGHT: (1, 0),
LEFT: (0, 0.5),
CENTER: (0.5, 0.5),
RIGHT: (1, 0.5),
BOTTOM_LEFT: (0, 1),
BOTTOM: (0.5, 1),
BOTTOM_RIGHT: (1, 1),
}
TOP_LEFT = crop.Crop.TOP_LEFT
TOP = crop.Crop.TOP
TOP_RIGHT = crop.Crop.TOP_RIGHT
BOTTOM_LEFT = crop.Crop.BOTTOM_LEFT
BOTTOM = crop.Crop.BOTTOM
BOTTOM_RIGHT = crop.Crop.BOTTOM_RIGHT
CENTER = crop.Crop.CENTER
LEFT = crop.Crop.LEFT
RIGHT = crop.Crop.RIGHT
def __init__(self, width=None, height=None, anchor=None):
"""
@ -56,26 +45,14 @@ class Fill(object):
self.anchor = anchor
def process(self, img):
cur_width, cur_height = img.size
horizontal_anchor, vertical_anchor = Fill._ANCHOR_PTS[self.anchor or \
Fill.CENTER]
ratio = max(float(self.width) / cur_width, float(self.height) / cur_height)
resize_x, resize_y = ((cur_width * ratio), (cur_height * ratio))
crop_x, crop_y = (abs(self.width - resize_x), abs(self.height - resize_y))
x_diff, y_diff = (int(crop_x / 2), int(crop_y / 2))
box_left, box_right = {
0: (0, self.width),
0.5: (int(x_diff), int(x_diff + self.width)),
1: (int(crop_x), int(resize_x)),
}[horizontal_anchor]
box_upper, box_lower = {
0: (0, self.height),
0.5: (int(y_diff), int(y_diff + self.height)),
1: (int(crop_y), int(resize_y)),
}[vertical_anchor]
box = (box_left, box_upper, box_right, box_lower)
img = img.resize((int(resize_x), int(resize_y)), Image.ANTIALIAS).crop(box)
return img
original_width, original_height = img.size
ratio = max(float(self.width) / original_width,
float(self.height) / original_height)
new_width, new_height = (int(original_width * ratio),
int(original_height * ratio))
img = img.resize((new_width, new_height), Image.ANTIALIAS)
return crop.Crop(self.width, self.height,
anchor=self.anchor).process(img)
class Crop(Fill):
@ -128,7 +105,7 @@ class Fit(object):
return img
class SmartCrop(_SmartCrop):
class SmartCrop(crop.SmartCrop):
def __init__(self, *args, **kwargs):
warnings.warn('The SmartCrop processor has been moved to'
' `imagekit.processors.crop.SmartCrop`, where it belongs.',