python 等比例裁剪图片

使用场景: 工作中,比如办理社保卡,或者办理员工卡等,我们会提供证件照片,往往我们提供的证件照片都不符合要求,这个时候就需要对照片进行裁剪,此时我们会去印刷打印店花个几元钱让店主帮忙裁剪,这个时候我们也可以发挥作为程序猿的优势,使用程序裁剪图片(适用于对裁剪效果要求不大的情况,若是要非等比例裁剪,还是建议去打印店操作🙂)

例如我们操作一个图片,原始像素为 531*300 代码示例

from PIL import Image


def changeImage(file_in, width, height, file_out):
    image = Image.open(file_in)
    w, h = image.size
    newwidth = width
    newheight = height
    if width > w and height > h:  # 放大
        if (width / w) > (height / h):  # 改变比例大的边
            newwidth = int(w * height / h)
        else:
            newheight = int(h * width / w)
    else:  # 缩小 或者根据比例改变
        if (w / width) > (h / height):
            newwidth = int(w * height / h)
        else:
            newheight = int(h * width / w)
    resized_image = image.resize((newwidth, newheight), Image.ANTIALIAS)
    resized_image.save(file_out)


file_in = C:/download/lufei.jpg   # 原始像素 531*300
width = 600
height = 500
file_out = C:/Users/chenping/Desktop/lufei1.jpg

changeImage(file_in, width, height, file_out)

效果:

经验分享 程序员 微信小程序 职场和发展