(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.

Answer from sdikby on Stack Overflow
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)

🌐
Imageio
imageio.readthedocs.io › en › v2.33.1 › examples.html
Imageio Usage Examples — imageio 2.33.1 documentation
import imageio.v3 as iio import io # from HTTPS web_image = "https://upload.wikimedia.org/wikipedia/commons/d/d3/Newtons_cradle_animation_book_2.gif" frames = iio.imread(web_image, index=None) # from bytes bytes_image = iio.imwrite("<bytes>", frames, extension=".gif") frames = iio.imread(bytes_image, index=None) # from byte streams byte_stream = io.BytesIO(bytes_image) frames = iio.imread(byte_stream, index=None) # from file objects class MyFileObject: def read(size:int=-1): return bytes_image def close(): return # nothing to do frames = iio.imread(MyFileObject()) import imageio.v3 as iio from pathlib import Path images = list() for file in Path("path/to/folder").iterdir(): if not file.is_file(): continue images.append(iio.imread(file)) Note, however, that Path().iterdir() does not guarantees the order in which files are read.
Discussions

python - BytesIO object to image - Stack Overflow
OSError: cannot identify image file <_io.BytesIO object at 0x00000000041FC9A8> More on stackoverflow.com
🌐 stackoverflow.com
cannot identify image file <_io.BytesIO object
There was an error while loading. Please reload this page · I am running the following code: More on github.com
🌐 github.com
8
October 23, 2018
pillow: image to bytes to image
The complement to load is save: from PIL import Image from io import BytesIO orig = Image.new(mode='RGBA', size=(240, 60)) stream = BytesIO() orig.save(stream, "PNG") new = Image.open(stream) Alternatively, the complement to tobytes is frombytes. 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.frombytes('RGBA', (240,60), stream.getvalue()) More on reddit.com
🌐 r/learnpython
3
4
December 31, 2021
Deploy model: io.BytesIO Error when reading an image via POST resized with JS ✅ - Part 1 (2019) - fast.ai Course Forums
I’m crossposting this on StackOverflow because is not really about the course, but likely some of us will hit: Basically python PIL rejects to read an image you have resized with Javascript canvas I resize an image on the client-side with Javascript: var reader = new FileReader(); reader.onload ... More on forums.fast.ai
🌐 forums.fast.ai
1
August 2, 2019
🌐
Google Groups
groups.google.com › g › kivy-users › c › -Pl4v-fohc0
How to load an image from a io.BytesIO object
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, format='jpeg') # "Rewind" the stream to the beginning so we can read its ...
🌐
ProgramCreek
programcreek.com › python › example › 1734 › io.BytesIO
Python Examples of io.BytesIO
""" with io.BytesIO() as f: f.write(json.loads(d['npy']).encode('latin-1')) f.seek(0) return np.load(f) ... def screenshot(self, png_filename=None, format='pillow'): """ Screenshot with PNG format Args: png_filename(string): optional, save file name format(string): return format, "raw" or "pillow” (default) Returns: PIL.Image or raw png data Raises: WDARequestError """ value = self.http.get('screenshot').value raw_value = base64.b64decode(value) png_header = b"\x89PNG\r\n\x1a\n" if not raw_value.startswith(png_header) and png_filename: raise WDARequestError(-1, "screenshot png format error") if png_filename: with open(png_filename, 'wb') as f: f.write(raw_value) if format == 'raw': return raw_value elif format == 'pillow': from PIL import Image buff = io.BytesIO(raw_value) return Image.open(buff) else: raise ValueError("unknown format")
🌐
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.
🌐
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 - Key Takeaway: Unlike normal files, BytesIO stores data in RAM, making it much faster for temporary operations. Let’s generate an image dynamically without saving it to disk. from io import BytesIO from PIL import Image # Create an image img = Image.new("RGB", (200, 100), color=(255, 0, 0)) # A red image # Save image to BytesIO buffer image_buffer = BytesIO() img.save(image_buffer, format="PNG") # Move to start of buffer image_buffer.seek(0) # Read and display the image size print(len(image_buffer.getvalue())) # Output: Size of image in bytes
🌐
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 - This example focuses on comparing the structural similarity of two images while highlighting the advantages of using in-memory operations with BytesIO. from io import BytesIO import numpy as np from PIL import Image from skimage.metrics import structural_similarity as ssim def images_are_similar(image1, image2): # Resize images to a common size resized_image1 = resize_image(image1) resized_image2 = resize_image(image2) # Convert images to grayscale using BytesIO gray_image1 = Image.open(BytesIO(resized_image1)).convert('L') gray_image2 = Image.open(BytesIO(resized_image2)).convert('L') # Conve
Find elsewhere
🌐
GitHub
github.com › python-pillow › Pillow › issues › 3431
cannot identify image file <_io.BytesIO object · Issue #3431 · python-pillow/Pillow
October 23, 2018 - I am running the following code: import requests from PIL import Image try: aux_im = Image.open(requests.get('https://www.bimbaylola.com/media/catalog/product/1/8/182BAC104_T2200_P_T_XX_1.jpg', stream=True).raw) except Exception as e: pr...
Author   python-pillow
🌐
Imageio
imageio.readthedocs.io › en › v2.32.0 › examples.html
Imageio Usage Examples — imageio 2.32.0 documentation
import imageio.v3 as iio import io # from HTTPS web_image = "https://upload.wikimedia.org/wikipedia/commons/d/d3/Newtons_cradle_animation_book_2.gif" frames = iio.imread(web_image, index=None) # from bytes bytes_image = iio.imwrite("<bytes>", frames, extension=".gif") frames = iio.imread(bytes_image, index=None) # from byte streams byte_stream = io.BytesIO(bytes_image) frames = iio.imread(byte_stream, index=None) # from file objects class MyFileObject: def read(size:int=-1): return bytes_image def close(): return # nothing to do frames = iio.imread(MyFileObject()) import imageio.v3 as iio from pathlib import Path images = list() for file in Path("path/to/folder").iterdir(): if not file.is_file(): continue images.append(iio.imread(file)) Note, however, that Path().iterdir() does not guarantees the order in which files are read.
🌐
Imageio
imageio.readthedocs.io › en › stable › examples.html
Imageio Usage Examples — imageio 2.37.3 documentation
import imageio.v3 as iio import io # from HTTPS web_image = "https://raw.githubusercontent.com/imageio/test_images/refs/heads/main/newtonscradle.gif" frames = iio.imread(web_image, index=None) # from bytes bytes_image = iio.imwrite("<bytes>", frames, extension=".gif") frames = iio.imread(bytes_image, index=None) # from byte streams byte_stream = io.BytesIO(bytes_image) frames = iio.imread(byte_stream, index=None) # from file objects class MyFileObject: def read(size:int=-1): return bytes_image def close(): return # nothing to do frames = iio.imread(MyFileObject()) import imageio.v3 as iio from pathlib import Path images = list() for file in Path("path/to/folder").iterdir(): if not file.is_file(): continue images.append(iio.imread(file)) Note, however, that Path().iterdir() does not guarantees the order in which files are read.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-io-bytesio-stringio
Python io.BytesIO and io.StringIO: Memory File Guide | DigitalOcean
August 3, 2022 - It is also possible to read a file and stream it over a network as Bytes. The io module can be used to convert a media file like an image to be converted to bytes.
🌐
Kaggle
kaggle.com › questions-and-answers › 360398
Error: cannot identify image file <_io.BytesIO object at 0x7f18047e4ef0> | Kaggle
for breed in top3breed: try: first_image = wptools.page(breed).get().data['image'][0] image_url = first_image['url'] r = requests.get(image_url) image = Image.open(BytesIO(r.content)) file_format = image_url.split(".")[-1] image.save(folder_name + "/" + breed + "." + file_format) except Exception as e: print(breed + ":" + str(e))` ... Please sign in to reply to this topic. ... Some time back I too faced this issue, this answer helped me back then. https://stackoverflow.com/questions/31077366/pil-cannot-identify-image-file-for-io-bytesio-object
🌐
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>
🌐
Fast.ai
forums.fast.ai › part 1 (2019)
Deploy model: io.BytesIO Error when reading an image via POST resized with JS ✅ - Part 1 (2019) - fast.ai Course Forums
August 2, 2019 - I’m crossposting this on StackOverflow because is not really about the course, but likely some of us will hit: Basically python PIL rejects to read an image you have resized with Javascript canvas I resize an image on the client-side with Javascript: var reader = new FileReader(); reader.onload = function (e) { el('image-picked').src = e.target.result; el('image-picked').className = ''; var image = new Image(); //compress Image image.onload=function...
🌐
Python.org
discuss.python.org › python help
"cannot identify image file <_io.BytesIO object" - Python Help - Discussions on Python.org
November 19, 2023 - Getting the error “cannot identify image file <_io.BytesIO object” , while adding contextily basemaps, The same code worked well till date · I thought I could guess the cause: the call to savefig expects a file name but you expect it to write into your BytesIO.
🌐
jdhao's digital space
jdhao.github.io › 2019 › 07 › 06 › python_opencv_pil_image_to_bytes
Convert PIL or OpenCV Image to Bytes without Saving to Disk · jdhao's digital space
October 6, 2020 - What if we want to resize the original image and convert it to binary data, without saving the resized image and re-read it from the hard disk? How should we do it? We can do it with the help of OpenCV or PIL. ... import cv2 im = cv2.imread('test.jpg') im_resize = cv2.resize(im, (500, 500)) is_success, im_buf_arr = cv2.imencode(".jpg", im_resize) byte_im = im_buf_arr.tobytes() # or using BytesIO # io_buf = io.BytesIO(im_buf_arr) # byte_im = io_buf.getvalue()
🌐
CodeRivers
coderivers.org › blog › io-bytesio-python
Python's `io.BytesIO`: A Comprehensive Guide - CodeRivers
February 22, 2026 - For example, you can use io.BytesIO to read an image file into memory, perform some image processing operations, and then write the modified image back to a file or send it over a network.
🌐
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 understanding is that this gives a stream of bytes, but may not provide ...