代码来自网友Jimmy Kuu和方石:
import Image
image = Image.open('01.jpg')
image.thumbnail((48, 48), Image.ANTIALIAS)
w, h = image.size
if w == 48 and h == 48:
image.save('thumb.jpg')
else:
image2 = Image.new(image.mode, (48, 48), (255, 255, 255))
if w < 48:
box = ((48 - w) / 2, 0, 24 + w / 2, 48)
else:
box = (0, (48 - h) / 2, 48, 24 + h / 2)
image2.paste(image, box)
image2.save('thumb.jpg')
这个更好一点
def get_Square_photo(imgname, outimgname, width):
"""
@param imgname:
@param outimgname:
@param
"""
img = Image.open(imgname, "r")
if img.size[0] > img.size[1]:
offset = int(img.size[0] - img.size[1]) / 2
img = img.transform((img.size[1], img.size[1]), EXTENT, (offset, 0, int(img.size[0] - offset), img.size[1]))
else:
offset = int(img.size[1] - img.size[0]) / 2
img = img.transform((img.size[0], img.size[0]), EXTENT, (0, offset, img.size[0], (img.size[1] - offset)))
img.thumbnail((width, width))
img.save(outimgname, 'png')