Python - Converting Image



Description

Image FormatWe already know that a image is a picture where the data is stored in rectangular grid of pixels.Every image has an format.The size of the image depends on the format of the image.

The most common image file formats are
1.jpg
2.tif
3.png
4.gif

In general jpg is the most used image file format.jpg format compresses the data to be very much smaller in the file.

Syntax

Following is the syntax of functions been used.
# Import Pillow:
from PIL import Image
# Load the original image:
object = Image.open(image)
#Remove the file extension with os module newfile = os.path.splitext(filename)[0]
concatenate the required extension newfile = newfile + ".png"
object.save(image)

Parameters

In this example, we will be passing the image file as the argument and then use the os module to split the extension and will concatenate the basefilename with required new extension
Note:If image is in same directory where your python program resides, you can give the image name itself. If the image resides in some other directory, you are supposed to define the complete path of the image.

Return value

The image with new extension will be saved to the local directory.

Example

The following example shows how to convert the extension from jpg to png.
import os
from PIL import Image
filename = "after_crop_1.jpg"
# loading the image
im = Image.open(filename)
filesize_a = os.path.getsize(filename)
print "File size :", filesize_a,"(in bytes)"
# removing the extension of the file
newfile = os.path.splitext(filename)[0]
newfile = newfile + ".png"
im.save(newfile)
filesize_b = os.path.getsize(newfile)
print "File size :", filesize_b,"(in bytes)"

Output:
after_crop_1.jpg file size: 14724 (in bytes)
after_crop_1.png file size : 96410 (in bytes)

The file size may vary depending on the file quality and the file size will be changed automatically once the format has been changed.
Advertisements