Rahul R

Mar 24, 20231 min

Resize Images using Python

Python Script to resize images in python without loosing aspect ratio. By using this script you can resize images without loss of aspect ration either by height or by width.

To install Pillow, use the pip module of Python:

python3 -m pip install Pillow

Scaling by width without losing the aspect ratio

The following is the basic script to resize an image using Pillow :

from PIL import Image
 
base_width = 300
 
img = Image.open('fullsized_image.jpg')
 
wpercent = (basewidth / float(img.size[0]))
 
height_size = int((float(img.size[1]) * float(wpercent)))
 
img = img.resize((basewidth, height_size), Image.ANTIALIAS)
 
img.save('resized_img.jpg')

The above code resizes the image at line 3. The script has a base_width of 300, height is automatically calculated by determining the percentage of 300 pixels with (img.size[0]) and we multiply it with the orginal height by that percentage which gives us the height_size. Using the image resize function we resize the image and the image is saved to the new file resized_img.jpg

Scaling by height without losing the aspect ratio

If the height is fixed and the width proportionally variable, it's pretty much the same thing, you just need to switch things around a bit:

from PIL import Image
 

 
base_height = 560
 
img = Image.open('fullsized_image.jpg')
 
height_size = (baseheight / float(img.size[1]))
 
wsize = int((float(img.size[0]) * float(hpercent)))
 
img = img.resize((height_size , baseheight), Image.ANTIALIAS)
 
img.save('resized_image.jpg')

Now in this case we change the base_width to base_height. In Line 3 we calculate the height percentage, to calculate the height percentage we use img.size[1] instead of img.size[0]. When using the size function size[0] gives you the width of the image and size[1] gives you the height of the image.

Using this we can resize the image without loss of aspect ratio using Pillow package.

    90
    0