Creating Graphic content using Python Pillow Library
Vishwas Patel
Posted on December 25, 2022
To create an image using the Python PIL library that displays graphic content like rectangle and a circle, you will need to follow these steps:
1.Install the PIL library by running
pip install pillow
2.Import the necessary modules:
from PIL import Image, ImageDraw
3.Create a blank image with a white background using the Image.new()
method:
# Create a blank image with a white background
image = Image.new('RGB', (400, 400), 'white')
4.Create a drawing context using the ImageDraw.Draw() method:
draw = ImageDraw.Draw(image)
5.Use the rectangle() method to draw a rectangle on the image:
# Draw a rectangle at (50, 50) with a width of 100 and a height of 200
draw.rectangle((50, 50, 150, 250), fill='red')
6.Use the ellipse() method to draw a circle on the image:
# Draw a circle at (200, 200) with a radius of 50
draw.ellipse((150, 150, 250, 250), fill='blue')
7.Save the image using the save() method:
image.save('image.png')
Here is the complete code that puts everything together:
from PIL import Image, ImageDraw
# Create a blank image with a white background
image = Image.new('RGB', (400, 400), 'white')
# Create a drawing context
draw = ImageDraw.Draw(image)
# Draw a rectangle
draw.rectangle((50, 50, 150, 250), fill='red')
# Draw a circle
draw.ellipse((150, 150, 250, 250), fill='blue')
# Save the image
image.save('image.png')
This code will create an image file named "image.png" that contains a red rectangle and a blue circle. You can then view the image using an image viewer or display it in a Python program using a library such as PyQt5 or tkinter.
Posted on December 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.