Introduction
Have you ever come across a situation where you need to edit or modify multiple images?
It is very tedious to work with each image one by one. If you need to apply the same changes to all the images, that is very time consuming and boring. But, using Python, you can do it quite quickly.
Let’s start playing with images.
Reading images and getting image details
Let’s see how we can read an image. The following is my solution structure.
I have a Python file named ImageManipulation.py and an image file named PythonImageFromGoogle.PNG in my folder.
To read the image present in the folder, you can use the following code.
-
-
- pythinImg = Image.open('PythonImageFromGoogle.PNG')
- print(pythinImg.size)
- print(pythinImg.format)
Here, I am trying to import an image from PIL. I will be using the Image filter in the following examples that I have imported with it now.
Size and Format will get you the size and format type of the image respectively.
Output
How to create a new image?
It is easy to create a new image in Python.
-
- newImage = Image.new('RGBA',(200,150),'blue')
- newImage.save('newImage.png')
“Image.new” will create a new image with width 200 and height 150. The image colour is blue.
"Save" will save the image in the same folder with the name provided here.
Output
Following is the folder structure after the execution. You can notice the newImage.png added in the folder.
Rotate the image and open it
You can rotate an image by whatever angle you want to rotate and save the image.
-
- pythinImg.rotate(180).save('PythonImageFromGoogle180.PNG')
- pythinImg_180 = Image.open('PythonImageFromGoogle180.PNG')
- pythinImg_180.show()
Here, the first line rotates the image by 180 degrees and saves the file. And in the third line, the rotated images open up.
Output
Following is the folder structure after the execution. You can notice the PythonImageFromGoogle180.PNG added in the folder.
Filter an Image
It is easy to apply a filter on images to make them visually better.
-
- image_sharp = pythinImg_180.filter( ImageFilter.SHARPEN )
-
- image_sharp.save( 'PythonImageFromGoogle180Sharpen.PNG' )
Output
Following is the folder structure after the execution. You can notice the PythonImageFromGoogle180Sharpen.PNG added in the folder.
-
- from PIL import Image,ImageFilter
-
-
- pythinImg = Image.open('PythonImageFromGoogle.PNG')
- print(pythinImg.size)
- print(pythinImg.format)
-
-
- newImage = Image.new('RGBA',(200,150),'blue')
- newImage.save('newImage.png')
-
-
- pythinImg.rotate(180).save('PythonImageFromGoogle180.PNG')
- pythinImg_180 = Image.open('PythonImageFromGoogle180.PNG')
- pythinImg_180.show()
-
-
- image_sharp = pythinImg_180.filter( ImageFilter.SHARPEN )
-
- image_sharp.save( 'PythonImageFromGoogle180Sharpen.PNG' )
Output
Please try it out, you will enjoy it. Happy coding!!!