I'm not sure what the resulting image should look like (do you have an example?), but if you want to unpack an packed image where each pixel has 12 bits into a 16-bit image, you could use this code:

import io
from PIL import Image

rawbytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\\x00\\\x00Z\x00\\\x00_\x00[\x00\\\x00\\\x00`\x00]\x00\\\x00^\x00_\x00\\\x00\\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\\x00^\x00\\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\\x00Z\x00\\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
im = Image.frombuffer("I;16", (5, 10), rawbytes, "raw", "I;12")
im.show()
Answer from Michiel Overtoom on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › pillow: image to bytes to image
r/learnpython on Reddit: pillow: image to bytes to image
December 31, 2021 -

My function accepts bytes to internaly opens them as a PIL.Image object. The function works as expected when bytes are passed to it. But I would like to write a couple of tests to it. So I need to generate images, turn them into bytes and pass them to my function so that it can turn it again back into an image.

Basically I wanna do something like this:

from PIL import Image
from io import BytesIO 
orig = Image.new(mode='RGBA', size=(240, 60))
image_bytes = orig.tobytes()
stream = BytesIO(image_bytes)
new = Image.open(stream) 

But what I don't understand is that it is not working and I get this Traceback:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Users/crane/PycharmProjects/my_project/venv/lib/python3.9/site-packages/PIL/Image.py", line 3030, in open
    raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x104f86950>
Discussions

How do I convert an bytes image from BytesIO to a PIL image in python? - Stack Overflow
Now I want to reverse the process and convert the image back to a PIL Image. How do I do this ? ... You can use the following syntax: image = Image.open(io.BytesIO(im_bytes)). More on stackoverflow.com
🌐 stackoverflow.com
python - PIL cannot identify image file for io.BytesIO object - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. I am using the Pillow fork of PIL and keep receiving the error · OSError: cannot identify image file <_io.BytesIO object at 0x103a47468> More on stackoverflow.com
🌐 stackoverflow.com
Loading image from bytes
File "C:\Program Files\Python37\lib\site-packages\PIL\Image.py", line 2822, in open raise IOError("cannot identify image file %r" % (filename if filename else fp)) OSError: cannot identify image file <_io.BytesIO object at 0x0000000003465F68> Here is the test code to use. More on github.com
🌐 github.com
15
September 28, 2019
python - How to write PNG image to string with the PIL? - Stack Overflow
I'd like to have several such images stored in dictionary. ... You can use the BytesIO class to get a wrapper around strings that behaves like a file. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Google Groups
groups.google.com › g › kivy-users › c › -Pl4v-fohc0
How to load an image from a io.BytesIO object
The picamera docs then shows how to load that into a PIL Image, as follows: import io import time import picamera from PIL import Image as PILImage # Create the in-memory stream stream = io.BytesIO() with picamera.PiCamera() as camera: camera.start_preview() time.sleep(2) camera.capture(stream, ...
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_images_bytesio.html
Example: Inserting images from a URL or byte stream into a worksheet — XlsxWriter
# # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2013-2025, John McNamara, jmcnamara@cpan.org # from io import BytesIO from urllib.request import urlopen import xlsxwriter # Create the workbook and add a worksheet. workbook = xlsxwriter.Workbook("images_bytesio.xlsx") worksheet = workbook.add_worksheet() # Read an image from a remote url. url = ( "https://raw.githubusercontent.com/jmcnamara/XlsxWriter/" + "master/examples/logo.png" ) image_data = BytesIO(urlopen(url).read()) # Write the byte stream image to a cell.
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python bytes to pil images
5 Best Ways to Convert Python Bytes to PIL Images - Be on the Right Side of Change
February 23, 2024 - Then, the array is converted to a PIL image using Image.fromarray(). For a quick and concise way to perform the conversion, utilize BytesIO with Image.open() in a one-liner.
🌐
Mellowd
mellowd.dev › python › using-io-bytesio
Using io.BytesIO() with Python - mellowd.dev
May 15, 2019 - #!/usr/bin/env python3 import io import matplotlib import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() b = io.BytesIO() plt.savefig(b, format='png') plt.close() b is now an in-memory object that can be used wherever a file is used. Attach it to your tweet and you’re set. If you do need to now dump this image to storage you can still do that.
🌐
Stack Overflow
stackoverflow.com › questions › 65639284 › how-do-i-convert-an-bytes-image-from-bytesio-to-a-pil-image-in-python
How do I convert an bytes image from BytesIO to a PIL image in python? - Stack Overflow
Now I want to reverse the process and convert the image back to a PIL Image. How do I do this ? ... You can use the following syntax: image = Image.open(io.BytesIO(im_bytes)).
Top answer
1 of 8
50

(This solution is from the author himself. I have just moved it here.)

SOLUTION:

# This portion is part of my test code
byteImgIO = io.BytesIO()
byteImg = Image.open("some/location/to/a/file/in/my/directories.png")
byteImg.save(byteImgIO, "PNG")
byteImgIO.seek(0)
byteImg = byteImgIO.read()


# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO)

The problem was with the way that Image.tobytes()was returning the byte object. It appeared to be invalid data and the 'encoding' couldn't be anything other than raw which still appeared to output wrong data since almost every byte appeared in the format \xff\. However, saving the bytes via BytesIO and using the .read() function to read the entire image gave the correct bytes that when needed later could actually be used.

2 of 8
5

On some cases the same error happens when you are dealing with a Raw Image file such CR2. Example: http://www.rawsamples.ch/raws/canon/g10/RAW_CANON_G10.CR2

when you try to run:

byteImg = Image.open("RAW_CANON_G10.CR2")

You will get this error:

OSError: cannot identify image file 'RAW_CANON_G10.CR2'

So you need to convert the image using rawkit first, here is an example how to do it:

from io import BytesIO
from PIL import Image, ImageFile
import numpy
from rawkit import raw
def convert_cr2_to_jpg(raw_image):
    raw_image_process = raw.Raw(raw_image)
    buffered_image = numpy.array(raw_image_process.to_buffer())
    if raw_image_process.metadata.orientation == 0:
        jpg_image_height = raw_image_process.metadata.height
        jpg_image_width = raw_image_process.metadata.width
    else:
        jpg_image_height = raw_image_process.metadata.width
        jpg_image_width = raw_image_process.metadata.height
    jpg_image = Image.frombytes('RGB', (jpg_image_width, jpg_image_height), buffered_image)
    return jpg_image

byteImg = convert_cr2_to_jpg("RAW_CANON_G10.CR2")

Code credit if for mateusz-michalik on GitHub (https://github.com/mateusz-michalik/cr2-to-jpg/blob/master/cr2-to-jpg.py)

Find elsewhere
🌐
Google Sites
sites.google.com › site › hellobenchen › home › wiki › python › bytes-image-cv2
BEN CHEN's Homepage - bytes image cv2
#convert to image · img2 = Image.fromarray(img2) #open bytes using Image directly · img3 = Image.open(BytesIO(content)) Google Sites · Report abuse · Page details · Page updated · Google Sites · Report abuse · This site uses cookies from Google to deliver its services and to analyze traffic.
🌐
Medium
medium.com › @abhishekshaw020 › understanding-bytesio-handling-in-memory-files-like-a-pro-e1b767339468
Understanding BytesIO: Handling In-Memory Files Like a Pro | by Abhishek Shaw | Medium
March 31, 2025 - ✅ Generating dynamic files — Need to create a report or an image on the fly? Use BytesIO to generate and serve files without ever saving them.
🌐
Bitbucket
hhsprings.bitbucket.io › docs › programming › examples › python › PIL › Image__Functions.html
Image Module - Functions — Pillow (PIL) examples - bitbucket.io
>>> from io import BytesIO >>> from PIL import Image >>> >>> xpmsrc = b"""\ ... /* XPM */ ... static char * cross_xpm[] = { ... "8 8 2 1", ... "* c #0000ff", ... ". c #ffffff", ... "..****..", ... "..*..*..", ... "********", ... "*.*..*.*", ... "*.*..*.*", ... "********", ... "..*..*..", ... "..****..", ... }; ... """ >>> img = Image.open(BytesIO(xpmsrc)) >>> mg.resize((8*10, 8*10)).save("cross.png") See also: save. ... https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.new, http://effbot.org/imagingbook/image.htm#tag-Image.new · >>> from PIL import Image >>> img = Image.new("RGB", (640, 480)) # mode, size, color(default: 0) >>> # ... (do something to img) ...
🌐
Imageio
imageio.readthedocs.io › en › v2.33.1 › examples.html
Imageio Usage Examples — imageio 2.33.1 documentation
In the future, this syntax will change to better match the URI standard by using fragments. The updated syntax will be "Path/to/file.zip#path/inside/zip/to/image.png".
🌐
GitHub
github.com › python-pillow › Pillow › issues › 4097
Loading image from bytes · Issue #4097 · python-pillow/Pillow
September 28, 2019 - import sys from PIL import Image from io import BytesIO # PNG data LEFT_THUMB = ( '\x89\x50\x4E\x47\x0D\x0A\x1A\x0A\x00\x00\x00\x0D\x49\x48\x44\x52\x00\x00' '\x00\x13\x00\x00\x00\x0B\x08\x06\x00\x00\x00\x9D\xD5\xB6\x3A\x00\x00\x01' '\x2E\x49\x44\x41\x54\x78\x9C\x95\xD2\x31\x6B\xC2\x40\x00\x05\xE0\x77\x10' '\x42\x09\x34\xD0\x29\x21\x82\xC9\x9C\x2E\x72\x4B\x87\x40\x50\xB9\xBF\x5B' '\x28\x35\xA1\xA4\x94\x76\x68\x1C\x1C\x74\xCD\x9A\xE8\x20\x0A\x12\xA5\x5A' '\xE4\x72\xC9\x75\x10\x6D\xDC\xCE\xF7\x03\x3E\xDE\x83\x47\xA4\x94\x68\x67' '\xB5\xD9\x4E\xBF\xBF\x3E\xE8\x78\x3C\x86\x6A\x3C\xCF\x43\x10\x04\x2
Author   python-pillow
🌐
Learning Machine
gallon.me › using-the-bytesio-class-in-python
Using the BytesIO Class in Python - Learning Machine
February 14, 2025 - You can wrap the bytes in a BytesIO to provide that interface: import io from PIL import Image # Pillow library for image processing # Simulated image bytes (normally you'd get this from a request) image_bytes = b'...' # Replace with actual image bytes # Wrap the bytes in a BytesIO object image_stream = io.BytesIO(image_bytes) # Open the image using PIL, which expects a file-like object image = Image.open(image_stream) image.show() # Display the image
🌐
Reddit
reddit.com › r/learnpython › using bytesio make bytes object save as a png to memory?
r/learnpython on Reddit: Using BytesIO make bytes object save as a png to memory?
June 15, 2016 -

So I'm writing a bit of spyware to learn the extents of python, and I'm running into an issue. I need to use BytesIO to save a bytes object to png through memory, and not hard drive. https://github.com/novazzz/screengrabber https://www.reddit.com/r/learnpython/comments/4o9bt8/how_did_this_code_turn_out/ If you have a suggustion that would work, great. It just can't save a png to memory and has to be able to be attached to an email.

🌐
Medium
medium.com › @sarthakshah1920 › harnessing-the-power-of-in-memory-buffers-with-bytesio-0ac6d5493178
Harnessing the Power of In-Memory Buffers with BytesIO | by Sarthak Shah | Medium
December 24, 2023 - Memory Usage: While suitable for small to medium-sized files, large files may increase memory consumption. Let’s delve into an example of in-memory image processing using the provided code snippet. This example focuses on comparing the structural similarity of two images while highlighting the advantages of using in-memory operations with BytesIO.
🌐
Streamlit
discuss.streamlit.io › using streamlit
PNG --> Bytes IO --> numpy conversion using file_uploader? - Using Streamlit - Streamlit
December 20, 2019 - st.file_uploader returns a io.BytesIO file when I upload an image. I’d like to cast this to a numpy array of shape (y,x,3) but am out of my depth when it comes to understanding how to use BytesIO objects. My current …