3

Maybe this is because I'm a newby to Python. But I don't seem to be able to resize and save images.

Can somebody help me by telling me what I'm doing wrong here? I'm resizing first, and secondly cropping an image to 256x256. The output is saved as the original image. Function call like: resizeAndCrop("path/to/image.png")

Current behavior is the script saving the image in the original size...

# 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)
11
  • 1
    resize() returns a resized copy of an image, so you need to assign the result of the operation otherwise the new image is lost. The same is true of crop() with the added wrinkle that "This is a lazy operation. Changes to the source image may or may not be reflected in the cropped image. To get a separate copy, call the load method on the cropped copy." Commented Feb 28, 2017 at 18:35
  • so you are performing crop and resize on the image, but nothing is happening and the same image as the original is being saved? Commented Feb 28, 2017 at 18:36
  • 1
    As in: newImage = im.resize((int(xNew),....... ? Commented Feb 28, 2017 at 18:36
  • @The4thIceman correct Commented Feb 28, 2017 at 18:36
  • 1
    @StevenRumbalski was first. I defer to him Commented Feb 28, 2017 at 18:41

1 Answer 1

2

As per the documentation: https://pillow.readthedocs.io/en/4.0.x/reference/Image.html

calling resize on an image "Returns a resized copy of this image." So you would need to assign the result to a new variable:

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

and for cropping the same applies, but it is noted in the docs that "Prior to Pillow 3.4.0, this was a lazy operation." So nowadays you will need to assign the call to crop to another variable as well

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.