如何在 Python 中保存调整大小的图像?

How to save a resized image in Python?

也许这是因为我是 Python 的新手。但我似乎无法调整大小和保存图像。

有人可以告诉我我做错了什么吗?我首先调整大小,然后将图像裁剪为 256x256。输出保存为原始图像。函数调用如:resizeAndCrop("path/to/image.png")

当前行为是脚本以原始大小保存图像...

# function for resizing and cropping to 256x256
def resizeAndCrop(imgPath):

    im = Image.open(imgPath)

    # remove original
    os.remove(imgPath)

    # Get size
    x, y = im.size

    # New sizes
    yNew = 256
    xNew = yNew # should be equal

    # First, set right size
    if x > y:
        # Y is smallest, figure out relation to 256
        xNew = round(x * 256 / y)
    else:
        yNew = round(y * 256 / x)

    # resize
    im.resize((int(xNew), int(yNew)), PIL.Image.ANTIALIAS)

    # crop
    im.crop(((int(xNew) - 256)/2, (int(yNew) - 256)/2, (int(xNew) + 256)/2, (int(yNew) + 256)/2))

    # save
    print("SAVE", imgPath)
    im.save(imgPath)

根据文档:https://pillow.readthedocs.io/en/4.0.x/reference/Image.html

调用图像调整大小"Returns a resized copy of this image."因此您需要将结果分配给新变量:

resizedImage = im.resize((int(xNew), int(yNew)), PIL.Image.ANTIALIAS)

对于裁剪同样适用,但文档中指出 "Prior to Pillow 3.4.0, this was a lazy operation." 所以现在您还需要将对裁剪的调用分配给另一个变量