Converting images to JPG format using Pillow in Python
Converting an Image to JPG Format in Python Using Pillow
Let’s see how to convert an image to JPG format in Python. PNGs are larger in size than JPGs. We also know that some applications may require smaller image sizes. Therefore, we need to convert from PNGs (larger) to JPGs (smaller).
For this task, we will use the Image.convert() method of the Pillow module.
Algorithm:
1. Import the image module from PIL and the os module.
2. Import the image to be converted using the Image.open() method.
3. Use the os.path.getsize() method to display the size of the image before conversion.
4. Convert the image using the Image.convert() method. Pass “RGB” as the argument.
5. Export the image using the Image.save() method.
6. Use the os.path.getsize() method to display the size of the converted image.
We will convert the following image.
# importing the module
from PIL import Image
import os
# importing the image
im = Image.open("geeksforgeeks.png")
print("The size of the image before conversion: ", end = "")
print(os.path.getsize("geeksforgeeks.png"))
# converting to jpg
rgb_im = im.convert("RGB")
# exporting the image
rgb_im.save("geeksforgeeks_jpg.jpg")
print("The size of the image after conversion : ", end = "")
print(os.path.getsize("geeksforgeeks_jpg.jpg"))
Output:
The size of the image before conversion : 26617
The size of the image after conversion : 18118