DEV Community

Vishwas Patel
Vishwas Patel

Posted on

Creating Graphic content using Python Pillow Library

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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

4.Create a drawing context using the ImageDraw.Draw() method:

draw = ImageDraw.Draw(image)
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

7.Save the image using the save() method:

image.save('image.png')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)