.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,x
representing the horizontal position, andy
representing 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 (
P
mode). - A Single integer or a tuple with a single integer for grayscale images (
M
mode).
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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Skill path
Data Science Foundations
Learn to clean, analyze, and visualize data with Python and SQL.Includes 15 CoursesWith CertificateBeginner Friendly55 hours - Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours