Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python PIL | tobytes() Method

  • Last Updated : 02 Aug, 2019

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!