Skip to main content

How to Resize Images in Python

Resizing images is a common task in programming, especially when preparing images for websites or mobile apps. Python offers a few libraries that make this task simple and efficient. By leveraging these tools, you can resize your images in several lines of code. This guide will show you how to resize images using two popular libraries, Pillow and OpenCV, providing clear examples and step-by-step explanations.

Understanding Image Resizing

Resizing an image involves altering its dimensions while maintaining or adjusting its aspect ratio. But why resize? Smaller images can be faster to upload, download, and display, which is particularly important for web performance. Moreover, resizing helps in maintaining consistency in presentations, especially in image galleries or thumbnails.

Using Pillow to Resize Images

Pillow, a fork of the original Python Imaging Library (PIL), simplifies image processing tasks. Let's explore how to use it.

First, you'll need to install Pillow. Open your terminal and type:

pip install Pillow

Here's a basic example of how to resize an image using Pillow:

from PIL import Image

# Open an image file
image = Image.open('sample.jpg')

# Define the size
new_size = (800, 600)

# Resize the image
resized_image = image.resize(new_size)

# Save the resized image
resized_image.save('resized_sample.jpg')

Explanation:

  • Image.open('sample.jpg'): Opens your file. Replace 'sample.jpg' with your file path.
  • new_size = (800, 600): Sets the desired new size (width, height).
  • image.resize(new_size): Resizes the image to the new dimensions.
  • resized_image.save('resized_sample.jpg'): Saves the resized image with a new name or location.

Maintaining Aspect Ratio with Pillow

Often, you'll want to resize images without distorting them. Let's see how we can maintain the aspect ratio.

from PIL import Image

def resize_with_aspect(image_path, base_width):
    img = Image.open(image_path)
    w_percent = (base_width / float(img.size[0]))
    h_size = int((float(img.size[1]) * float(w_percent)))
    img = img.resize((base_width, h_size), Image.Resampling.LANCZOS)
    img.save('resized_aspect.jpg')

resize_with_aspect('sample.jpg', 500)

Explanation:

  • base_width: Determines the desired width.
  • w_percent and h_size: Calculate the proportionate height to maintain the aspect ratio.
  • Image.Resampling.LANCZOS: A high-quality downsampling filter.

Using OpenCV for Image Resizing

OpenCV is another powerful library widely used in computer vision tasks. It also supports image resizing.

First, install OpenCV:

pip install opencv-python

Here's a simple example using OpenCV:

import cv2

# Read an image
image = cv2.imread('sample.jpg')

# Define the dimensions
width = 640
height = 480
dimensions = (width, height)

# Resize the image
resized_image = cv2.resize(image, dimensions, interpolation=cv2.INTER_AREA)

# Save the resized image
cv2.imwrite('resized_opencv.jpg', resized_image)

Explanation:

  • cv2.imread('sample.jpg'): Loads the image from a file.
  • dimensions: Specifies the new size.
  • cv2.resize(image, dimensions, interpolation=cv2.INTER_AREA): Resizes the image. The INTER_AREA interpolation is ideal for reducing the size.

Conclusion

Resizing images in Python is efficient and straightforward with the help of libraries like Pillow and OpenCV. Whether you're preparing images for web performance or ensuring uniform presentation, these tools provide the flexibility and power you need.

Experiment with the examples given, and explore further into Python's capabilities. If you're interested in more Python techniques, check out our Master Python Programming page for comprehensive tutorials and guides.

Popular posts from this blog

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...