4. Image frombytes


4.1. Frombytes

Use the Image.frombytes(mode, size, data, decoder_name='raw', *args) method to return an image from pixel data in a buffer.
In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data).
Note that this function decodes pixel data only, not entire images. If you have an entire image in a string, wrap it in a BytesIO object, and use open() to load it.
mode - The image mode. See: Modes.
size - The image size.
data - A byte buffer containing raw data for the given mode.
decoder_name - What decoder to use.
args - Additional parameters for the given decoder.

4.2. XBM frombytes

The code below takes a xbm file and converts it to an image
from PIL import Image

xbm_src = b"""\
#define ambulance_width 32
#define ambulance_height 32
static char ambulance_bits[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x3f,0x00,0x01,0x00,
0x40,0x00,0x01,0x00,0xa0,0x00,0x01,0x70,0x20,0x01,0x01,0x70,0x20,0x02,0x01,
0xfc,0xe1,0x7c,0x01,0xfc,0x01,0x80,0x01,0xfc,0x01,0x80,0x01,0x70,0x00,0xc0,
0x01,0x70,0x00,0xc0,0x01,0x00,0x00,0x80,0xc1,0x07,0xe0,0x83,0x21,0x08,0x10,
0x84,0x91,0x13,0xc8,0x89,0x49,0x24,0x24,0x92,0x29,0x28,0x14,0x94,0x2f,0xe8,
0x17,0xf4,0x20,0x08,0x10,0x04,0x40,0x04,0x20,0x02,0x80,0x03,0xc0,0x01,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
"""
im_1 = Image.frombytes("1", (32, 32), xbm_src, decoder_name="xbm")
# im_1.show()
im_1.save("image/image_frombytes_1.jpg")

im_L = Image.frombytes("L", (32, 32), xbm_src, decoder_name="xbm")
im_L.save("image/image_frombytes_L.jpg")
../_images/compare_frombytes.png