Resize and save image in python
Resizing images is an integral part of the web, whether to display images on your website or app, store lower-resolution images, or generate a training set for neural networks. Python offers a rich set of options to perform some of the routine image resizing tasks. This article will walk you through those options and look at ImageKit - a cloud-based, ready-to-use solution that offers real-time image manipulation. We will look at Make sure you have a recent version of Python installed on your system, preferably Python 3.6+, then spin up a virtual environment. When we get to ImageKit later in this article, you will need to
sign up for a free account on ImageKit's website. The free plan has access to all the features we need for image resizing and other transformations. We will be using an image by Asad from Pexels for all examples in this article. This image is also hosted on ImageKit. Pillow is one of the most popular options for performing basic image manipulation tasks such as cropping, resizing, or adding watermarks. Install the latest version of Pillow with Pillow provides the resize() method, which takes a (width, height) tuple as an
argument. We read our image using the Here is how our resized image looks like The The thumbnail method resizes the image in place without returning an image object. Therefore, make sure to save the file with a different name. The So, if we want to crop an image from the (300,300) point to (700,900) point, the code would be There is an easier method of using
Here is our sample image cropped by 600px from all sides. Image cropped with PillowYou should check out the pillow handbook for more complex image operations. Bonus: Adding a watermark to an imageTo add watermarks, we need to use the ImageDraw and ImageFont methods. The ImageDraw module provides simple-to-use APIs for working with 2D graphics, from creating polygons to writing text. ImageFont sets the font of the watermark text.
Make sure to choose a font that is available on your system. You can set the position, fill, anchor, or language. You can also download a font of your choice and provide the path to it. Here is the sample output - Applying a simple watermark on the imageResizing images using OpenCV
First, let's install the latest opencv for Python using pip.
Note that we are using OpenCV 4.5 for this tutorial. Resizing with OpenCVAlthough OpenCV is a viable choice for image resizing, it is best suited for heavy-duty tasks like object detection. Stick to Pillow for basic image manipulation or scroll below to see how ImageKit does that. Resizing
images can be done by
Cropping an image with OpenCVOpenCV uses a NumPy array under the hood for representing images. We can leverage array slicing to extract the part of the pixels we need, i.e., crop the image. Since this is a 2D array, we need to specify the start and end coordinates, just like we did while cropping images with Pillow. Though, the syntax here is slightly different. If we want to crop an image starting at (0,0) point to (2732, 3640) point, then we can do this with OpenCV as shown below
You can read more about image processing tutorials from OpenCV. Using ImageKit to resize and crop imagesBoth Pillow and OpenCV are good options to resize and crop images. But these solutions require extensive setup and maintenance in line with the changing business needs. This might not be the best utilization of your or your team's time when tools like ImageKit.io can do the same job for you with minimal effort. ImageKit.io is a real-time image and video optimization, manipulation, and storage product that can help you do basic resizing and cropping on your images and more. You have the flexibility to either upload your images to the integrated media library or attach your existing cloud storage or servers to ImageKit and start delivering optimized files. Several image and video optimizations are done automatically, considering multiple factors, whereas resizing, cropping, and other transformations can be done by simply modifying the URL in real-time. Setup with ImageKitIn our example, we have already uploaded the sample image to ImageKit.
You should sign up for a free account on ImageKit that comes with an ample amount of storage and delivery bandwidth. You can download the original image from Pexels from here and upload it to your media library. We will be using ImageKit's Python SDK to create the resized and cropped image URLs. You can install this SDK using the following command -
Basic resizing by changing height and widthResizing images in ImageKit is simple. Just add the required dimension transformation to the URL, and you will get the resized image in real-time. For example, to get the sample image with a width of 200px, the URL will be - Image resized to width 200px using URL-based transformation parametersWhile this is a simple string append operation, the Python SDK makes the code simpler and readable. Example of generating a URL at width 200px
with the Python SDKSimilarly, if we want to get a 400 x 300px resized image from ImageKit, the URL will contain height and width transformation parameters.
The corresponding code with the Python SDK will be
There are several other image transformation options with ImageKit. You can read about them from the product documentation or from the Python SDK documentation. Cropping images with a specific aspect ratioAnother transformation available in ImageKit is the aspect ratio transformation. You can use it with either the width or the height transformation to fix the output image's aspect ratio and transformations. For example, to get an image at 800px width with an aspect ratio 4:3, the URL will be
Cropping options available with ImageKitIn the above examples, if the output aspect ratio doesn't match the input aspect ratio, the image gets cropped around the center of the original by default. However, ImageKit gives us multiple cropping options that can prevent cropping on the image and help us get the required output. Let's look at some of the standard cropping options below. 1. No cropping - Forcing Requested Dimensions You can do this by adding the The image is force-fit to the 400x200px sizeIn the Python SDK, this can be specified
using the
2. Fit inside a container The The image fits inside the 400x200px box3. Fit outside a container Opposite to the The resulting image is larger than the 400x200px dimension specified4. Pad an image If you still want the resulting image to match the output
dimension requested but not get cropped, you can use the
The resulting URL is Image with padding using URL a parameterYou can see grey-colored padding around the image, which perfectly fits the 400 x 200px output dimensions without cropping the image. Bonus: Adding watermarks to an image using ImageKitImageKit offers more than 40+ different real-time transformation parameters for images. We can use them to add both image and text overlays to our images and control how and where they are displayed on our images. You can refer to the complete overlays documentation here. Let's look at an example to add text on the image in the top-left corner of our base image. Here we specify the text, its font size, and font color in the URL itself.
The resulting image URL is Adding watermark to the image with a URL parameter
ConclusionHere's a quick summary of what we learned today. We looked at three different ways of resizing images in Python.
How do I resize and save an image in Python?Practical Data Science using Python
The Image module from pillow library has an attribute size. This tuple consists of width and height of the image as its elements. To resize an image, you call the resize() method of pillow's image class by giving width and height.
How do I resize an image in Python?resize() Returns a resized copy of this image.. Syntax: Image.resize(size, resample=0). Parameters:. size – The requested size in pixels, as a 2-tuple: (width, height).. resample – An optional resampling filter. This can be one of PIL. Image. NEAREST (use nearest neighbour), PIL. Image. ... . Returns type: An Image object.. How do I resize an image to the same size in Python?To resize an image, you call the resize() method on it, passing in a two-integer tuple argument representing the width and height of the resized image. The function doesn't modify the used image; it instead returns another Image with the new dimensions.
How do I resize an image in a list in Python?You can resize multiple images in Python with the awesome PIL library and a small help of the os (operating system) library. By using os. listdir() function you can read all the file names in a directory. After that, all you have to do is to create a for loop to open, resize and save each image in the directory.
|