Convert an image size using Python ready-to-use function


How to convert or scale an image size using Python?

Install the following modules if you haven’t installed them already:

pip install pillow

Ready to use Python function to convert or scale or re-size an image using Pytho ready-to-use function:

def image_scale(ImageFile, ScalePercent):
    # Open the image file
    img = Image.open(ImageFile)

    # Get the original size of the image
    width, height = img.size

    # Scale the image to 50% of its original size
    new_width = int(width * ScalePercent/100)
    new_height = int(height * ScalePercent/100)

    # Resize the image to the new size
    new_img = img.resize((new_width, new_height))

    # Save the resized image
    new_img.save("scaled_image.jpg")

Write your main code as a sample below,

from PIL import Image

image_scale("flower.jpg", 200)

The output of the code is,

Original Image
Scaled Image to 200%
How does the function work?

This code is written in Python and uses the Pillow library to resize an image. In short, this code takes an image file and a scale percent as input, resizes the image to the specified percentage of its original size, and saves the resized image to a file. Here’s a step-by-step explanation of how it works:

  1. Import the Image module from the Pillow library
  2. Define a function named image_scale which takes two arguments: ImageFile and ScalePercent.
  3. The function opens an image file using the Image.open method and stores the image in the img variable.
  4. The size of the original image is obtained using the img.size method, which returns a tuple of the width and height of the image.
  5. The new width and height of the image are calculated by multiplying the original width and height by the ScalePercent divided by 100.
  6. The resize method of the img object is used to resize the image to the new size, which is stored in the new_img variable.
  7. Finally, the resized image is saved to a file named “scaled_image.jpg” using the save method.

Leave a Reply

Your email address will not be published. Required fields are marked *