如果宽>长也是可以缩放的。
from PIL import Image
#说明:依据木桶原理,默认单张图片缩放,例如需要正方形模板,长大于宽的,缩放到宽与正方形相等
wanlen = 1280
wanwidth = 720
infile="G:/PythonIO/newBG2.PNG"
cutyes = 1
def solveImage(infile):
outfile = infile.replace(".", "out.")
img = Image.open(infile)
# img.show()
# grayimg = img.convert('L')
# grayimg.save(outfile)
lenmore = True
imgsize = img.size
if (imgsize[0] / imgsize[1] > wanlen / wanwidth):
print(imgsize)
lenmore = True
relength = int(imgsize[0] * wanwidth / imgsize[1])
# print("len more" + str(relength))
out = img.resize((relength, wanwidth), Image.ANTIALIAS) # 抗毛刺
else:
print(imgsize)
lenmore = False
rewidth = int(imgsize[1] * wanlen / imgsize[0])
out = img.resize((wanlen, rewidth), Image.ANTIALIAS)
if cutyes == 1:
# 裁剪
if lenmore:
left = int(relength / 2 - wanlen / 2)
cropped = out.crop((left, 0, left + wanlen, wanwidth))
cropped.save(outfile)
else:
right = int(rewidth / 2 - wanwidth / 2)
cropped = out.crop((0, right, wanlen, right + wanwidth))
cropped.save(outfile)
else:
out.save(outfile)
cutyes = 0
solveImage(infile)