Open In App

Python PIL | tobytes() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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

Last Updated : 02 Aug, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads