在调整图像大小之前,您需要正确裁剪图像。基本思想是确定源图像的最大矩形区域,其与缩略图具有相同的宽高比(宽度与高度),然后在调整大小到缩略图的尺寸之前修剪掉(裁剪)其周围的任何多余部分。这是一个计算此类裁剪区域的大小和位置的函数:
def cropbbox(imagewidth,imageheight, thumbwidth,thumbheight):
""" cropbbox(imagewidth,imageheight, thumbwidth,thumbheight)
Compute a centered image crop area for making thumbnail images.
imagewidth,imageheight are source image dimensions
thumbwidth,thumbheight are thumbnail image dimensions
Returns bounding box pixel coordinates of the cropping area
in this order (left,upper, right,lower).
"""
# determine scale factor
fx = float(imagewidth)/thumbwidth
fy = float(imageheight)/thumbheight
f = fx if fx < fy else fy
# calculate size of crop area
cropheight,cropwidth = int(thumbheight*f),int(thumbwidth*f)
# for centering use half the size difference of the image and the crop area
dx = (imagewidth-cropwidth)/2
dy = (imageheight-cropheight)/2
# return bounding box of centered crop area on source image
return dx,dy, cropwidth+dx,cropheight+dy
if __name__=='__main__':
print("===")
bbox = cropbbox(1024,768, 128,128)
print("cropbbox(1024,768, 128,128): {}".format(bbox))
print("===")
bbox = cropbbox(768,1024, 128,128)
print("cropbbox(768,1024, 128,128): {}".format(bbox))
print("===")
bbox = cropbbox(1024,1024, 96,128)
print("cropbbox(1024,1024, 96,128): {}".format(bbox))
print("===")
bbox = cropbbox(1024,1024, 128,96)
print("cropbbox(1024,1024, 128,96): {}".format(bbox))
确定作物面积后,调用im.crop(bbox)
然后打电话im.thumbnail(...)
在返回的图像上。