Python: Resizing and Fitting an Image to an Exact Size

twitter logo github logo ・1 min read

Often, when working on image analysis in Python, you’d want to resize your images to uniform dimensions (usually, a power of 2). Here is one simple and proven way to resize an image of arbitrary size, down to the exact dimensions you want. If the new dimensions do not match the original ratio, the image will be cropped, starting from the center, in order to match the newly desired ratio.

from PIL import Image, ImageOps

original_image = Image.open("path/to/image")
size = (512, 512)
fit_and_resized_image = ImageOps.fit(original_image, size, Image.ANTIALIAS)

with help from StackOverlow

twitter logo DISCUSS (1)
markdown guide

Thanks! This is one of the good tips about python and IMG. And if you want to see some else: wardtina.quora.com/How-to-Create-U...

Classic DEV Post from Jul 30 '19

Save the planet, clean your mailbox

Preslav Rachev profile image
A software engineer working on his own stuff. Might see me writing advocating about strong developer culture, or rambling about Java / Python / Go

dev.to now has dark theme. 🌝

Go to the "misc" section of your settings and select night theme

P.S. It's the best move you can make for your dev career.