Python:Pillow .putpixel()
Anonymous contributor
Published Jun 20, 2024
Contribute to Docs
The .putpixel() method in Pillow is used to insert pixels onto an image. It is primarily used to set the color of an individual pixel, but it can also be used for other purposes such as changing pixel transparency or creating different shapes within the image.
Syntax
Image.putpixel(xy, color)
Image: The image on which the pixel color is to be set.xy: Specifies the coordinates of the pixel where the color will be placed,xrepresenting the horizontal position, andyrepresenting the vertical position.color: Specifies the color for the pixel, which can be:- An RGB tuple (3 integers) for true color images.
- An RGBA tuple (4 integers) for true color with transparency.
- An Integer for a color index in indexed color images (
Pmode). - A Single integer or a tuple with a single integer for grayscale images (
Mmode).
Example
The example below demonstrates the use of the .putpixel() method:
from PIL import Image# Define the dimensions of the imagewidth, height = 200, 200# Create a new image with RGB mode and black backgroundimg = Image.new('RGB', (width, height), color='black')# Add a blue pixel at the specified positionblue_pixel_position = (50, 50)blue_color = (0, 0, 255)# Add a red pixel at the specified positionred_pixel_position = (100, 100)red_color = (255, 0, 0)# Add a green pixel at the specified positiongreen_pixel_position = (150, 150)green_color = (0, 255, 0)# Set pixels to desired colorsimg.putpixel(red_pixel_position, red_color)img.putpixel(green_pixel_position, green_color)img.putpixel(blue_pixel_position, blue_color)img.show()
The above code generates the output image as follows:
![]()
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pillow on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to clean, analyze, and visualize data with Python and SQL.
- Includes 15 Courses
- With Certificate
- Beginner Friendly.55 hours