Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Open CV
  • scikit-image
  • pycairo
  • Pyglet
  • Python
  • Numpy
  • Pandas
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Django
  • Flask
  • R
Open In App
Next Article:
Create transparent png image with Python - Pillow
Next article icon

Generate square or circular thumbnail image with Python – Pillow

Last Updated : 17 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites: Pillow, Numpy

In the word “THUMBNAIL” the word THUMB means short. A thumbnail is the compressed preview image of the original image or a Thumbnail is the smaller version of an image. In simple words, the thumbnail is the smaller image that represents the larger/original image. 

Usually, the shape of the thumbnail is dependent on the original image, but in this article, we are going to generate the circular and square thumbnail image using Pillow Library in Python.

Installation:

For installing pillow and NumPy libraries, write the following command on your command prompt.

pip install pillow  pip install numpy

Example 1: Opening image using Pillow Library.

Python

# importing necessary libraries
from PIL import Image
  
# opening the image from the storage using 
# Image.open() function
orig_img=Image.open('Geekwork/sebastian-molina.jpg')
  
# showing the image using show() function
orig_img.show()
                      
                       

Output:

Example 2: Generating circular thumbnail image using Pillow Library.

Approach:

  • Convert the image into NumPy array using NumPy library.
  • Now create a new mask image using PIL.Image.new() function by pass the mode, image size, and color, then draw the image using PIL.Image.Draw.Draw() function by passing the size of the new mask image and let be stored in the variable named “draw”.
  • Make the circle on the mask image using ImageDraw.Draw.peislice() function by passing four points to define a boundary, starting angle=0, ending angle=360 this creates the circle on the mask image and with them pass fill parameter for filling the color in an image.
  • Convert the mask image to numpy array then stack the array depth-wise along with the third axis using numpy.dstack() function and pass the original image array and mask image array as we had converted in above steps to get the circular image, and let it be stored in the variable named as “npImage”.
  • As this “npImage” is in array format we have to convert this array into an image, this is done with the help of PIL.Image.fromarray() function into this pass npImage as a parameter and let it be stored in the variable named as “final_image”.
  • As we had generated the circular image.

Below is the full implementation:

Python

# importing necessary libraries
from PIL import Image, ImageDraw
import numpy as np
  
# opening the image from
# the storage using Image.open() function
orig_img=Image.open('sebastian-molina.jpg')
  
# getting height and width of 
# an image using size() function
height,width=orig_img.size
  
# converting image to numpy array
npImage=np.array(orig_img)
  
# Creating mask image in L mode with same image size
new_img = Image.new('L', orig_img.size,0)
  
# drawing on mask created image using Draw() function
draw = ImageDraw.Draw(new_img)
  
# making circle on mask image using pieslice() function
draw.pieslice([0,0,height,width],0,360,fill=255)
  
# Converting the mask Image to numpy array
np_new=np.array(new_img)
  
# stack the array sequence
# (original image array with mask image) depth wise
npImage=np.dstack((npImage,np_new))
  
# converting array to an image using fromarray() function
final_img = Image.fromarray(npImage)
  
# making thumbnail using thumbnail() 
# function by passing the size in it
final_img.thumbnail((500,500))
  
# saving the circular thumbnail Image
final_img.save('Circular_thumbnail.png')
                      
                       

Output:

Example 3: Generating square thumbnail image using Pillow Library.

Approach:

  • Check the three conditions if height==width or height>width or width>height if the dimension of the image falls in any of the last two conditions.
  • Then we have to create the new mask image using new() function with the longest side/dimension of the image.
  • Then paste the original image on the new mask image by using paste() function and pass the original image with calculated dimensions which we will discuss in the explanation of the example.
  • Now we will get the square image by following the above steps.
  • Now we have to generate the thumbnail image, we can do this by using PIL.Image.thumbnail() method by passing the size as a parameter, then save this using PIL.Image.save() method and pass the name of the image with standard image format.

Below is the full implementation:

Python

# importing necessary libraries
from PIL import Image, ImageDraw
import numpy as np
  
# function to generate squared image
def square_thumb(thum_img,width,height):
    
    # checking if height and width are
    # are equal then return image as it is
    if height == width:
        return thum_img
  
    # checking if height is greater than width
    elif height > width:
        
        # creating the new mask image of size i,e height of Image
        square_img = Image.new(thum_img.mode, (height, height))
          
        # pasting the original image on mask image
        # using paste() function to make it square
        square_img.paste(thum_img, ((height - width) // 2,0))
          
        # returning the generated square image
        return square_img
  
    # if width is greater than height
    else:
        
        # creating the new mask image of size i,e width of Image
        square_img = Image.new(thum_img.mode, (width, width))
          
        # pasting the original image on mask image using paste()
        # function to make it square
        square_img.paste(thum_img, (0, (width - height) // 2))
          
        # returning the generated square image
        return square_img 
  
# main function  
if __name__ == "__main__":
    
    # opening the image from the storage
    # using Image.open() function
    orig_img=Image.open('sebastian-molina.jpg')
  
    # extracting width and height of an
    # image from the image size 
    w,h = orig_img.size
  
    # calling the function by passing
    # image width and height as a parameter
    sq_img = square_thumb(orig_img,w,h)
  
    # generating square thumbnail of
    # required size using thumbnail() function
    sq_img.thumbnail((400,400))
  
    # saving the thumbnail using save function
    sq_img.save('Square_thumbnail.jpg')
                      
                       

Output:

Explanation: We had created the function to generate a square image by passing the image, it’s width and height as a parameter. In the function we had checked three conditions on the basis of that we had generated the square image.

  • In the first condition, we had checked if the height of the image is equal to the width or not if True then we had returned the image as it is because when height and width are equal images is already in the square shape.
  • In the second condition, if the height of an image is greater than the width, then we created the new mask image using Image.new() function by passing the mode of an image and size as it’s the height (i.e, height, height) and paste the original image on the created mask image using paste() function by passing original image and dimension at which original image is pasted on mask image i.e, from calculated dimension (subtracting the height of original image with a width of the original image and then divide it by 2) to 0, so that original image can be perfectly pasted on the mask image.
  • In the third condition, if the width of an image is greater than the height, then we did the same process as we had done in the second condition, but the only change is we had created the mask image of size as it’s the width (i.e, width, width) and in case of pasting we had to pass original image and dimension i.e, from 0 to the calculated dimension (by subtracting the width of the original image with a height of the original image and then divide it by 2 ) so that original image can be perfectly pasted on the mask image.


Next Article
Create transparent png image with Python - Pillow
author
srishivansh5404
Improve
Article Tags :
  • Python
  • Technical Scripter
  • Python-pil
  • Technical Scripter 2020
Practice Tags :
  • python

Similar Reads

  • Create transparent png image with Python - Pillow
    To create a transparent png using Python3, the Pillow library is used. The Pillow library comes with python itself. If python is unable to find Pillow library then open the command prompt and run this command:- pip install Pillow Note: If you got any problem installing Pillow using pip, then install
    3 min read
  • Python PIL | Image.thumbnail() Method
    PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files,
    2 min read
  • Create and save animated GIF with Python - Pillow
    Prerequisites: pillow In this article, we are going to use a pillow library to create and save gifs. GIFs: The Graphics Interchange Format(gif) is a bitmap image format that was developed by a team at the online services provider CompuServe led by American computer scientist Steve Wilhite on 15 June
    3 min read
  • How to Concatenate image using Pillow in Python ?
    Prerequisites: Python Pillow Concatenate image means joining of two images. We can merge any image whether it has different pixels, different image formats namely, 'jpeg', 'png', 'gif', 'tiff', etc. In python, we can join two images using the Python image library also known as the pillow library. In
    3 min read
  • How to merge images with same size using the Python 3 module pillow?
    In this article, the task is to merge image with size using the module pillow in python 3.  Python 3 module pillow : This is the update of Python Imaging Library. It is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and savi
    2 min read
  • Change image resolution using Pillow in Python
    Prerequisites: Python pillow PIL is the Python Imaging Library which provides the python interpreter with an in-depth file format support, an efficient internal representation, and fairly powerful image processing capabilities. Changing the resolution of an image simply means reducing or increasing
    2 min read
  • Change the ratio between width and height of an image using Python - Pillow
    Python Imaging Library (expansion of PIL) is the de facto image processing package for the Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. This module is not preloaded with Python. So to install it execute the following command in
    2 min read
  • Add padding to the image with Python - Pillow
    Prerequisites: Pillow(python library) Padding is the space between the contents, the container, and the border. An image can be considered content to some container and extra padding can be added to it. This article depicts how this can be done.  Padding can be added by straightaway supplying the va
    2 min read
  • Python | Working with the Image Data Type in pillow
    In this article, we will look into some attributes of an Image object that will give information about the image and the file it was loaded from. For this, we will need to import image module from pillow. Image we will be working on : size() method - It helps to get the dimensions of an image. IMG =
    2 min read
  • Convert PNG to ICO with Pillow in Python
    In this article, we will convert PNG to ICO using pillow in Python. Convert PNG to ICO with Pillow in Python Before moving further first let us understand what is PNG and ICO. The PNG stands for Portable Network Graphic. It is often used to store web graphics. The png image can be used with transpar
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences