你需要在調整大小之前正確地裁剪圖像。基本思路是確定具有與縮略圖圖像相同縱橫比(寬高比)的源圖像的最大矩形區域,然後在調整縮略圖的尺寸之前裁剪(剪裁)任何多餘的周圍區域。這裏是將計算這樣的剪切區域的大小和位置的功能:
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's dimensions
thumbwidth, thumbheight are thumbnail image's 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 compute half the size difference of the image & crop area
dx = (imagewidth-cropwidth)/2
dy = (imageheight-cropheight)/2
# return bounding box of crop area
return dx, dy, dx+cropwidth, dy+cropheight
if __name__=='__main__':
print "==="
bbox = cropbbox(1024, 768, 128, 128)
print "cropbbox(1024, 768, 128, 128):", bbox
print "==="
bbox = cropbbox(768, 1024, 128, 128)
print "cropbbox(768, 1024, 128, 128):", bbox
print "==="
bbox = cropbbox(1024, 1024, 96, 128)
print "cropbbox(1024, 1024, 96, 128):", bbox
print "==="
bbox = cropbbox(1024, 1024, 128, 96)
print "cropbbox(1024, 1024, 128, 96):", bbox
確定裁剪區域後,調用im.crop(bbox)
然後調用圖像im.thumbnail(...)
返回。
嘿,這真的很有幫助。非常感謝。 – ensnare 2010-10-11 14:49:24
您可以避免必須裁剪原始圖像,以確定縮放圖像的大小,以便將結果放在縮略圖的邊界內,但不一定完全填滿。 – martineau 2010-10-11 20:06:58
對於任何感興趣的人,我使用Ruby做了類似的事情:http://stackoverflow.com/a/14917213/407213 – Dorian 2013-02-17 18:44:52