注意到上面的建议,并使其向上扩展最大高度/宽度之内/向下。这里它的Python代码,并且还增加了对旋转的东西而限制一个内保持:
DEF _resize(图像,尺寸,旋转=无): “”” 调整大小的图像被尽可能接近到指定的尺寸图像是一个 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
是的,规范需要扩展以定义实际进行的智能调整大小。这个算法听起来合理。我会试试看。 – 2010-06-09 19:15:16