Image conversion in Python using PIL (PNG ⇄ JPG, WEBP ⇄ PNG)

Here we are going to use PIL(Python Imaging Library) or pillow library which is widely used for image processing in python and the most important class in the Python Imaging Library is the Image class, defined in the module with the same name.

You can create instances of this class in several ways; either by loading images from files, processing other images, or creating images from scratch.

To load an image from a file, use the open() function in the Image module:

from PIL import Image
img = Image.open('sample.jpg')
img.show()

The above code will read the sample.jpg image and then display it.

Image Conversion #

Image.convert() returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”.

save(fp, format) takes two input parameter, first file path(fp) to save the converted file and second the file format to convert into.

  1. Convert JPG to PNG
from PIL import Image
img = Image.open('sample.jpg').convert('RGB')
img.save('png_image.png', 'png')
  1. Convert PNG to JPG
from PIL import Image
img = Image.open('sample.png').convert('RGB')
img.save('jpg_image.png', 'jpeg')
  1. Convert PNG to WEBP
from PIL import Image
img = Image.open('sample.png').convert('RGB')
img.save('webp_image.webp', 'webp')
  1. Convert WEBP to PNG
from PIL import Image
img = Image.open('sample.webp').convert('RGB')
img.save('png_image.png', 'png')
  1. Convert JPG to WEBP
from PIL import Image
img = Image.open('sample.jpg').convert('RGB')
img.save('webp_image.png', 'webp')
  1. Convert WEBP to JPG
from PIL import Image
img = Image.open('sample.webp').convert('RGB')
img.save('jpg_image.jpg', 'jpeg')

Tags:

Python