I have many images of different sizes in my directory, however i want to resize them all by a certain ratio, let's say 0.25 or 0.2, it should be a variable i can control from my code and i want the resulting images to be an output in another directory.
I looked into this approach supplied by this previous question How to resize an image in python, while retaining aspect ratio, given a target size?
Here is my approach, aspectRatio = currentWidth / currentHeight heigth * width = area So, height * (height * aspectRatio) = area height² = area / aspectRatio height = sqrt(area / aspectRatio) At that point we know the target height, and width = height * aspectRatio. Ex: area = 100 000 height = sqrt(100 000 / (700/979)) = 373.974 width = 373.974 * (700/979) = 267.397
but it lacks lots of details for example:how to transform these sizes back on the image which libraries to use and so on..
Edit: looking more into the docs img.resize looks ideal (although i also noticed .thumbnail) but i can't find a proper example on a case like mine.
from PIL import Image
ratio = 0.2
img = Image.open('/home/user/Desktop/test_pic/1-0.png')
hsize = int((float(img.size[1])*float(ratio)))
wsize = int((float(img.size[0])*float(ratio)))
img = img.resize((wsize,hsize), Image.ANTIALIAS)
img.save('/home/user/Desktop/test_pic/change.png')
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