Convert an image size using Python ready-to-use function
- tinyytopic.com
- 0
- on Feb 13, 2023
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,
![](https://tinyytopic.com/wp-content/uploads/2023/02/flower.jpg)
![](https://tinyytopic.com/wp-content/uploads/2023/02/scaled_image.jpg)
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:
- Import the
Image
module from thePillow
library - Define a function named
image_scale
which takes two arguments:ImageFile
andScalePercent
. - The function opens an image file using the
Image.open
method and stores the image in theimg
variable. - 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. - The new width and height of the image are calculated by multiplying the original width and height by the
ScalePercent
divided by 100. - The
resize
method of theimg
object is used to resize the image to the new size, which is stored in thenew_img
variable. - Finally, the resized image is saved to a file named “scaled_image.jpg” using the
save
method.