ImageFile module in Pillow

Pillow is a successor project of Python’s original image processing module, the Python Imaging Library (PIL), which is in discontinuation since 2011. It provides various functionalities for working on digital images in Python. Apart from basic image operations like open, display, rotate, save etc, you can use the Pillow module for filtering images and changing color spaces too. The current version of Pillow accepts various formats, such as PNG, JPEG, GIF, PPM, TIFF and BMP.
In this tutorial, you will learn in particular about the ImageFile module of Pillow in Python.

Installing Pillow

To use the ImageFile, first of all, you need to install the Pillow module. You can do the same by running the below command on your terminal.

pip install pillow

Once you have the Pillow module installed, you can proceed to explore it further.

ImageFile module: Support for open() and save()

  • Saving an image
    from PIL import Image
    import PIL
    image= Image.open(r"C:\Users\varsh\Desktop\images1.jpeg")
    image = image.save("saved.jpg")

    The above code will save the image file from the specified path and save it with the specified name.

  • Opening an image
    from PIL import Image
    image = Image.open(r"C:\Users\varsh\Desktop\images1.jpeg")
    image.show()

    The above code opens the image file whose path is specified in any available image viewer.

ImageFile module: Support for decoding an image

A Parser class is present in the ImageFile module and can be used to decode(parse) a given image, piece by piece. The code for the said operation:

from PIL import ImageFile
fp = open("images1.jpeg", "rb")
p = ImageFile.Parser()
while 1:
    s = fp.read(1024)
    if not s:
        break
    p.feed(s)
im = p.close()
im.save("parsed_copy.jpg")

You can store the parsed copy of the image using the save() as shown.

Some other modules provided by Pillow for Image Processing include ImageMath, ImageMorph, ImageFilter etc.
Each of these Pillow modules provides you with various image processing options. You should try exploring them too!

Follow this link for the official documentation and source code for ImageFile  in Pillow:
ImageFile

Also read, Get the Basic image information with Pillow | Python

Leave a Reply

Your email address will not be published.