Python PIL tobytes() method

Python PIL tobytes() Method

PIL is the Python Imaging Library, which provides image editing capabilities for the Python interpreter. The image module provides a class of the same name to represent a PIL image. The module also provides factory functions for loading images from files and creating new images.

Image.tobytes() Returns the image as a bytes object.

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

Arguments:

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

Returns: A bytes object.

Images used:
Python PIL tobytes() method

# Importing Image module from PIL package
from PIL import Image
  
#creating an image object
img = Image.open(r"C:UsersSystem-PcDesktoptree.jpg")
  
# using tobytes
img.tobytes("xbm", "rgb")
print(img)

Output:

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

Another example: Here, using the same image, the encoder name is changed to hexadecimal.

Images used:
Python PIL tobytes() method

# Importing Image module from PIL package
from PIL import Image
  
#creating an image object
img = Image.open(r"C:UsersSystem-PcDesktoptree.jpg")
  
# using tobytes
img.tobytes("hex", "rgb")
print(img)

Output:

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

Leave a Reply

Your email address will not be published. Required fields are marked *