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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With