Python Pillow – Using the Image Module

Python Pillow – Using the Image Module

In this article, we’ll see how to use PIL’s Image module in Python. First, let’s see how to install PIL.

Installation:

Linux: Type the following in your Linux terminal.

pip install Pillow

Install pip through the terminal.

sudo apt-get update
sudo apt-get install python-pip

Working with the Image Module

Here, we’ll go through some of the methods and properties provided by the Image module, as follows.

  • Open Image
  • Save Image
  • Image Resizing
  • Rotate Image
  • Crop Image
  • Resize an image and more.

Let’s discuss each one with the help of some examples.

1. Opening an Image:

To open an image using PIL, we use the open() method.

Syntax: PIL.Image.open(fp, mode='r', formats=None)

# importing Image from PIL
from PIL import Image
 
# open an image
img = Image.open('gfg.png')

Output:

Python Pillow - Using the Image Module

2. Retrieving the Image’s Dimensions:

To retrieve the image’s size, we’ll use the Image.size property provided by the image object.

Syntax: Image.size

from PIL import Image
   
with Image.open("gfg.png") as image:
    width, height = image.size
 
print((width, height))

Output:

(200, 200)

3. Saving Changes in the Image

To save the image, we use the Image.save() method.

Syntax: Image.save(fp, format=None, **params)

Parameters:

  • fp – A filename (string), pathlib.Path object, or file object.
  • format – Optional format override. If omitted, the format to use is determined by the filename’s extension. This parameter should always be used if using a file object instead of a filename.
  • options – Additional parameters for the image writer.

Returns: None

from PIL import Image
   
img = Image.open("gfg.png")
 
img.save("logo.jpg")

Output:

Python Pillow - Using the Image Module

4. Image Rotation:

Image rotation requires an angle as a parameter to rotate the image.

Syntax: Image.rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)

Parameters:

  • angle – The angle in degrees counterclockwise.
  • resample – An optional resampling filter.
  • expand – The optional expand flag. If true, expands the output image to accommodate the entire rotated image.
  • center – The optional center of rotation (a 2-tuple). The origin is the top-left corner. The default is the center of the image.
  • translate – An optional translation after the rotation (a 2-tuple).
  • fillcolor – Optional color to use for the area outside the rotated image.
from PIL import Image
 
img = Image.open("gfg.png")
 
rot_img = img.rotate(180)
 
rot_img.save("rotated_gfg.png")

Output:

Python Pillow - Using the Image Module

Original Image

Python Pillow - Using the Image Module

Rotated Image

5.Crop the Image:

Image.crop(box) takes a 4-tuple (left, top, right, bottom) of pixel coordinates and returns a rectangular region from the image.

Syntax: PIL.Image.crop(box = None)

Parameters:

  • box – A 4-tuple defining the left, top, right, and bottom pixel coordinates.

Return type: Image (returns a rectangular region as a (left, top, right, bottom) tuple).

Returns: An image object.

from PIL import Image
 
# open image and get size
img = Image.open("gfg.jpg")
width, height = img.size
 
# cropped image using coordinates
area = (0, 0, width/2, height/2)
crop_img = img.crop(area)
crop_img.save("cropped_image.jpg")

Output:

Python Pillow - Using the image module

Cropped Image

6. Resizing an Image:

Image.resize(size) is used to resize an image. Here, the size is provided as a 2-tuple of width and height.

Syntax: Image.resize(size, resample=0)

Parameters:

  • size – The requested size in pixels, as a 2-tuple: (width, height).
  • resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (uses nearest neighbors), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, PIL.Image.NEAREST is set.

Return type: An image object.

from PIL import Image
 
img = Image.open("gfg.png")
width, height = img.size
    
#resizing the image
img = img.resize((width//2, height//2))
       
img.save("resized_picture.png")

Output:

Python Pillow - Using the Image Module

Resized Image

7. Paste one image onto another:

The second argument can be a 2-tuple (specifying the top-left corner) or a 4-tuple (left, top, right, bottom) – in which case the size of the pasted image must match the size of the bounding box, or None, which is equivalent to (0, 0).

Syntax:

PIL.Image.Image.paste(image_1, image_2, box=None, mask=None)

<p>Or

<p><code>image_object.paste(image_2, box=None, mask=None)

<p><strong>Parameters:

<ul>
<li><strong>image_1/image_object:</strong> This is the image to which the other image is to be pasted. </li>
<li><strong>image_2</strong> : The source image or pixel values (integer or tuple). </li>
<li><strong>box</strong> <strong>:</strong> An optional 4-tuple giving the area to paste. If a 2-tuple is used, it is taken as the top-left corner. If omitted or not present, the source file is pasted at the top-left corner. </li>
<li><strong>mask</strong> : An optional mask image. </li>
</ul>
<p>If an image is given as the second argument and no third argument, the box defaults to (0, 0) and the second argument is interpreted as a mask image. </p>
<pre><code class="language-python line-numbers">from PIL import Image
 
img1 = Image.open("gfg.jpg")
 
#pasting img2 on img1
img2 = Image.open("gfg.png")
img1.paste(img2, (50, 50))
 
img1.save("pasted_picture.jpg")

Output:

Python Pillow - Using the image modulefrom PIL import Image   img = Image.open("gfg.png")        #Flipping the image by 180 degrees horizontally transposed_img = img.transpose(Image.FLIP_LEFT_RIGHT)          transposed_img.save("transposed.png")

Output:

Python Pillow - Using the Image Module

Original Image

Python Pillow - Using the Image Module

Transposed Image

9. Creating a Thumbnail:

This method creates a thumbnail of the opened image. It does not return a new image object, but rather modifies the currently opened image object in-place. If you do not want to modify the original image object, you can create a copy and then apply this method to it. This method also evaluates the size of the image to maintain the image’s aspect ratio.

Syntax: Image.thumbnail(size, resample=3)

Parameters:

  • size – The requested size.
  • resample – Optional resampling filter.

Return type: Image object.

from PIL import Image
 
img = Image.open("gfg.png")
 
img.thumbnail((200, 200))
 
img.save("thumb.png")

Output:

Python Pillow - Using the Image Module

200 x 200 pixel thumbnail

Leave a Reply

Your email address will not be published. Required fields are marked *