接受上面的建议,使其在最大高度/宽度内放大/缩小。这里是它的python代码,还增加了对旋转物体的支持,同时保持在限制范围内:
def _resize(image, dimensions, rotate=None): """ 调整图像的大小以尽可能接近指定的尺寸。图像是 django 图像模型字段。
Will both scale up and down the image to meet this while keeping the proportions
in width and height
"""
if image and os.path.isfile(image.path):
im = pil.open(image.path)
logging.debug('resizing image from %s x %s --> %s x %s ' % (im.size[0], im.size[1], dimensions[0], dimensions[1]))
if rotate:
logging.debug('first rotating image %s' % rotate)
im = im.rotate(90)
srcWidth = Decimal(im.size[0])
srcHeight = Decimal(im.size[1])
resizeWidth = srcWidth
resizeHeight = srcHeight
aspect = resizeWidth / resizeHeight # Decimal
logging.debug('resize aspect is %s' % aspect)
if resizeWidth > dimensions[0] or resizeHeight > dimensions[1]:
# if width or height is bigger we need to shrink things
if resizeWidth > dimensions[0]:
resizeWidth = Decimal(dimensions[0])
resizeHeight = resizeWidth / aspect
if resizeHeight > dimensions[1] :
aspect = resizeWidth / resizeHeight
resizeHeight = Decimal(dimensions[1])
resizeWidth = resizeHeight * aspect
else:
# if both width and height are smaller we need to increase size
if resizeWidth < dimensions[0]:
resizeWidth = Decimal(dimensions[0])
resizeHeight = resizeWidth / aspect
if resizeHeight > dimensions[1] :
aspect = resizeWidth / resizeHeight
resizeHeight = Decimal(dimensions[1])
resizeWidth = resizeHeight * aspect
im = im.resize((resizeWidth, resizeHeight), pil.ANTIALIAS)
logging.debug('resized image to %s %s' % im.size)
im.save(image.path)
else:
# no action, due to no image or no image in path
pass
return image