Python PIL Image.frombytes() method
Python PIL Image.frombytes() 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.
PIL.Image.frombytes() creates a copy of the image memory from the pixel data in the buffer. In its simplest form, the function requires three arguments (mode, size, and unpacked pixel data).
Syntax: PIL.Image.frombytes(mode, size, data, decoder_name='raw', *args)
Arguments:
mode – The image mode. See Mode.
size – The image size.
data – A byte buffer containing the raw data for the given mode.
decoder_name – The decoder to use.
args – Additional arguments for the given decoder.
Returns: An image object.
# importing image object from PIL
from PIL import Image
# using tobytes data as raw for frombyte function
tobytes = b'xd8xe1xb7xebxa8xe5 xd2xb7xe1'
img = Image.frombytes("L", (3, 2), tobytes)
# creating list
img1 = list(img.getdata())
print(img1)
Output:
[120, 100, 56, 225, 183, 235]
Another example: Here we use different raw data (tobytes).
# importing image object from PIL
from PIL import Image
# using tobytes data as raw for frombyte function
tobytes = b'xbfx8cdxbax7fxe0xf0xb8txfe'
img = Image.frombytes("L", (3, 2), tobytes)
# creating list
img1 = list(img.getdata())
print(img1)
Output:
[191, 140, 100, 186, 127, 224]