DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Start Coding With Google Cloud Workstations
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Why I Started Using Dependency Injection in Python
  • How to Convert Between PDF and TIFF in Java

Trending

  • Beyond Microservices: The Emerging Post-Monolith Architecture for 2025
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  1. DZone
  2. Coding
  3. Languages
  4. How to Display and Convert Images in Python

How to Display and Convert Images in Python

Python continues to grow by the day. This introductory tutorial walks you through the process to load, display, and convert images in Python.

By 
DZone Editorial user avatar
DZone Editorial
·
Nov. 15, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
3.3K Views

Join the DZone community and get the full member experience.

Join For Free

Python is gaining more attention and attraction than most other programming languages today. It's gained that popularity for a variety of reasons. It is both object-oriented and procedural, it's open-sourced and extensible, it's portable, and it has library support. Most importantly, however, is that Python is simple to code and very readable.

To illustrate how easy some things are to do in Python, we'll take a quick look at working with images. We’ll show how to load and display an image using Python, how to get image information using Python, and how to convert image formats using Python.


Crash Course on Python | Enroll for Free Today*

*Affiliate link. See Terms of Use.

Of course, to use images in Python, you need to have Python installed. Additionally, you will want to make sure you have the Pillow module installed. Installing the Pillow module can be done using the simple command line directive of:

Shell
 
pip install pillow


This will install an updated version of the Python Image Library (PIL), which will allow you to load and use images. Once you've installed Pillow, you are ready to start working with images.

Loading and Displaying an Image in Python

Writing an application to display an image in Python can be done with just a couple of lines of code as shown in Listing 1:

Listing 1: Img.py: Loading an Image in Python

Python
 
from PIL import Image
image = Image.open('image.jpg')
image.show()


The code in Listing 1 starts by importing the Image library. With the library loaded, you can load an image by call in the Image.open() method and assign the return value to a variable. With the image loaded, you are ready to display the image by calling the show() method on your image variable. If you run Listing 1 in a directory that contains an image named image.jpg, the image will be displayed. The following shows the image being displayed on a Windows system:

A screenshot of an image being displayed on a Windows system using Python.

Showing Image Properties Using Python

In addition to showing an image, the Image class provides a number of other properties and methods that can be used with images. Some of the key properties include:

  • filename: The name of the image file
  • format: The file format such as JPG, GIF
  • mode: The image mode such as RGB, RFBA, CMYK, or YCbCr
  • size: The image size in pixels displayed as a width, height tuple
  • width: The width of the image in pixels
  • height: The height of the image in pixels
  • is_animated: Indicates if the image is more than one frame. True if it is, False if it is not. This attribute is not included in all images.

Listing 2 shows how simple it is to load an image called ani.gif and display a bunch of its attributes. The image is included in this article just before the code:

An example of an animated GIF displayed via Python.


Listing 2: Img.py:  Displaying Image Attributes Using Python

Python
 
from PIL import Image
 
image = Image.open('ani.gif')
 
print("Filename: ", image.filename)
print("Format: ", image.format)
print("Mode: ", image.mode)
print("Size: ", image.size)
print("Width: ", image.width)
print("Height: ", image.height)
print("Is Animated: ", (getattr(image, "is_animated", False)))
 
image.close()   # close image file


It is worth noting that the ani.gif image is an animated gif, so when this listing is executed, the following information is displayed:

Filename: ani.gif

Format: GIF

Mode: P

('Size: ', (500, 500))

('Width: ', 500)

('Height: ', 500)

('Is Animated: ', True)

You can see that the animated gif is 500 by 500 pixels, it is indeed a GIF, and it is animated. In addition to the properties shown in Listing 2, there are two others you can check.

The first of these properties is palette. This is the color palette table if one is included with the image. The value is None if there is not a palette. For the ani.gif shown above, the color palette information that is shown when calling the property is:

Python
 
<PIL.ImagePalette.ImagePalette object at 0x000000000358CB88>


For the original JPG image used in Listing 1, the palette information was None.

The final property is info. Info is a dictionary object that allows for various non-image information to be shared. 

New to Python? Check this out: Python for Beginners: An Introductory Guide to Getting Started

Saving an Image

Opening an image was as simple as calling the open() method. Saving an image in Python is just as simple. You simply call save() and pass in the name you want used to save your image. This method will save the image in the format identified by the extension on the filename you pass in. Listing 3 opens the image.jpg file used in Listing 1 and saves it as a gif file by changing the filename that is passed to save().

Listing 3: Saving a File in Python

Python
 
from PIL import Image
 
image = Image.open('image.jpg')
image.save("NewImage.gif")


The save() method can receive a file object instead of a filename. It also can have two additional parameters passed that specifies the format you want used to save the file. The formats include BMP, DIB, EPS, GIF, ICO, JPEG, PCX, PNG, TIFF, and a multitude of others. The format would be specified as the second parameter as such:

Python
 
image.save("NewImage", format="BMP")


Summary

Python is and will continue to be very popular. This was a relatively short article because it is relatively easy to work with images in Python! You learned how to open an image in Python. You also saw how to obtain information about the image and how to then save a copy of the image in a different format.

Python (language) Image conversion Object type (object-oriented programming)

Opinions expressed by DZone contributors are their own.

Related

  • Start Coding With Google Cloud Workstations
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Why I Started Using Dependency Injection in Python
  • How to Convert Between PDF and TIFF in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!