Skip to content

Instantly share code, notes, and snippets.

@tomvon
Created June 8, 2014 22:59
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save tomvon/ae288482869b495201a0 to your computer and use it in GitHub Desktop.
Save tomvon/ae288482869b495201a0 to your computer and use it in GitHub Desktop.
Python script to resize an image while keeping the original aspect ratio.
#Resizes an image and keeps aspect ratio. Set mywidth to the desired with in pixels.
import PIL
from PIL import Image
mywidth = 300
img = Image.open('someimage.jpg')
wpercent = (mywidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((mywidth,hsize), PIL.Image.ANTIALIAS)
img.save('resized.jpg')
@hamzaavvan
Copy link

Exactly what I was looking for. Thanks mate @tomvon

@pynista
Copy link

pynista commented Nov 28, 2020

thank you!

@baxik88
Copy link

baxik88 commented Jan 26, 2021

Thanks!

@RishiRatanPandey
Copy link

helped a lot!

@aruna09
Copy link

aruna09 commented Apr 23, 2022

Hey does this conversion lead to lossy coversion? or loss less?

@tomvon
Copy link
Author

tomvon commented Apr 24, 2022

Hi @aruna09 ! Good question. I wrote that script many years ago and haven't actually used PIL (now Pillow) lately. I would recommend checking the latest docs https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html. I know for JPEG images you can set the compression level from 0 (fast, lossy) to 100 (slower, lossless?).

@ShivaGuntuku
Copy link

Thanks, code helped a lot !!

@AbdelilahChahbouni
Copy link

thank you

@Hemanthkumar2112
Copy link

thanks

@rakshitasupadhya
Copy link

Thanks for the code but ANTIALIAS is deprecated for 3.11 version of python. I have used Image.LANCZOS instead but quality is compromised. Can you please help?

@pritamsay
Copy link

It is reducing the colors. Which I don't want, that'swhy trying to find something which reduces the size but will not change the quality.
Original Size 31MB
After Size 4.55MB
Sorry, I can't upload the images here also because Github also not allowing me to upload file size above 10MB.

Alternatively, I want a code that should reduce the size 'just below 10MB'.

@pritamsay
Copy link

Thanks for the code but ANTIALIAS is deprecated for 3.11 version of python. I have used Image.LANCZOS instead but quality is compromised. Can you please help?

Yes Bro, same problem. What to do? I too don't understand.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment