Let’s first open an image so we can resize it.
from PIL import Image
file = "C://Users/ABC/Boat.jpg"
img = Image.open(file)
img.show()
After opening an image you can use the .resize() method on it to create a new image with a new size.
img.resize((x, y))
After opening an image you can use the .resize() method on it to create a new image with a new size.
img.resize((x, y))
img = img.resize((448,299))
img.show()
So, what happen if new size being passed to resize method is not proportionate to the original size?
In this case PIL will simply stretch the image to make it fit the new size. Let’s see an example.
img = img.resize((700,300))
img.show()
You can also get the size of an image using the .size property in PIL.
You don’t need to use parenthesis and you can simply print an image’s size as: print(img.size)
Let’s demonstrate getting the size of an image with an example:
from PIL import Image
file = "C://Users/ABC/Boat.jpg"
img = Image.open(file)
print(img.size)
(640, 427)
from PIL import Image
file = "C://Users/ABC/Boat.jpg"
img = Image.open(file)
img = img.resize((int(img.size[0]*0.2),int(img.size[1]*0.2)))
img.show()
In this Python Tutorial, we’ve seen how to resize an image and different scenarios regarding the new size.
We have also seen hot to get the size of an image and we saw an example regarding how to make use of this information.
You can really see the power of PIL library in image processing as well as basic image editing tasks through these operations.