简体   繁体   中英

Python PIL - Resize Images

I'm trying to change the size of an image, turning larger images into smaller images and vice versa, with PIL. I have done various tests, but I cannot get the result I want. Here are the tests I did with a 900x1600 image:

Same input every time: Image

size = (1080, 1080)
userImage = Image.open("./Images/UsersImages/001.png")
userImage.resize(size)
userImage.show()
size = (1080, 1080)
userImage = Image.open("./Images/UsersImages/001.png")
userImage.thumbnail(size, Image.ANTIALIAS)
userImage.show()
userImage = Image.open("./Images/UsersImages/001.png")
userImageWidth, userImageHeight = userImage.size

leftBorder = 4
topBorder = userImageHeight / 5
rightBorder = 154
bottomBorder = 3 * userImageHeight / 5
userImage = userImage.crop((leftBorder, topBorder, rightBorder, bottomBorder))

newsize = (1080, 1080)
userImage = userImage.resize(newsize)
userImage.show()
userImage = Image.open("./Images/UsersImages/001.png")
userImageWidth, userImageHeight = userImage.size
    
if userImageWidth > 1080:
    bottomBorder = (userImageWidth - 1080) / 2
    topBorder = bottomBorder
else:
    bottomBorder, topBorder = 0, 0

if userImageHeight > 1080:
    leftBorder = (userImageHeight - 1080) / 2
    rightBorder = leftBorder
else:
    leftBorder, rightBorder = 0, 0

userImage = userImage.crop((leftBorder, topBorder, rightBorder, bottomBorder))
userImage.show()

In most cases, the photo remains exactly the same as before. In cases with crop, it is cut very small.

How can I resize any image to 1080x1080? I don't care if the photo is stretched. The important thing is that any type of image, whether larger or smaller, is resized to 1080x1080.

Use userImage = userImage.resize(size) , because resize() returns a copy of the image, resized; it doesn't actively resize the image.

size = (1080, 1080)
userImage = Image.open(f"./Images/UsersImages/001.png")
userImage = userImage.resize(size) ### EDITED LINE
userImage.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM