Saturday, September 27, 2025
HomeLanguagesPython PIL | tobytes() Method

Python PIL | tobytes() Method

PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.

Image.tobytes() Return image as a bytes object

Syntax: Image.tobytes(encoder_name=’raw’, *args)

Parameters:

encoder_name – What encoder to use. The default is to use the standard “raw” encoder.
args – Extra arguments to the encoder.

Returns: A bytes object.

Image Used:




   
  
# Importing Image module from PIL package
from PIL import Image
  
# creating a image object
img = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg")
  
# using tobytes
img.tobytes("xbm", "rgb")
print(img)


Output:

PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x2D39DED2BE0

Another Example: Here using same image with change in encoder name to hex.

Image Used:




   
  
# Importing Image module from PIL package
from PIL import Image
  
# creating a image object
img = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg")
  
# using tobytes
img.tobytes("hex", "rgb")
print(img)


Output:

PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x27845B91BE0
RELATED ARTICLES

Most Popular

Dominic
32322 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6690 POSTS0 COMMENTS
Nicole Veronica
11857 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11913 POSTS0 COMMENTS
Shaida Kate Naidoo
6804 POSTS0 COMMENTS
Ted Musemwa
7073 POSTS0 COMMENTS
Thapelo Manthata
6763 POSTS0 COMMENTS
Umr Jansen
6768 POSTS0 COMMENTS