import io
from PIL import Image

img = Image.open(fh, mode='r')
roi_img = img.crop(box)

img_byte_arr = io.BytesIO()
roi_img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()

With this, I don't have to save the cropped image on my disk and I am able to retrieve the byte array from a PIL cropped image.

Answer from Evelyn Jeba 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

PIL Image to bytes and saving it as jpg is not working
You are saving it wrong. You need to save it using the PIL library because in addition to the bytes that make up the data of a JPEG file there are certain headers and encoding steps needed before putting the data into a JPEG file format. The PIL library does this for you. You can fix your code by changing it to this: from PIL import Image img = Image.open("test.jpg") img.thumbnail((128,128), Image.ANTIALIAS) img.save("123.jpg", "JPEG") More on reddit.com
🌐 r/learnpython
9
2
January 16, 2020
python - Convert PIL image to bytearray - Stack Overflow
Sign up to request clarification or add additional context in comments. ... This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:~.save, with a BytesIO parameter for in-memory data. More on stackoverflow.com
🌐 stackoverflow.com
August 28, 2016
python - Convert PIL Image to Bytes, getting Error - Stack Overflow
Traceback (most recent call last): ... '_io.BytesIO' object has no attribute 'get_value' ... It just outputs 0. Those are the only two suggestions I have found and they are not working for me. Is it an issue with my versions? I have Python 3.7.3 and PIL 6.1.0 ... I'm doing some operations using PIL before saving it, but I left it out in this code to simplify the problem ... Sign up to request ... More on stackoverflow.com
🌐 stackoverflow.com
November 13, 2019
python - PIL: Convert Bytearray to Image - Stack Overflow
I have working code for the ... output image is actually not totally broken. So I have to work with bytearrays ... Save this answer. ... Show activity on this post. If you manipulate with bytearrays, then you have to use io.BytesIO. Also you can read a file directly to a bytearray. Copyimport os import io import PIL.Image as Image ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pillow Documentation
pillow.readthedocs.io › en › stable › reference › Image.html
Image module - Pillow (PIL Fork) 12.3.0 documentation
Returns the image converted to an X11 bitmap. ... This method only works for mode “1” images. ... A string containing an X11 bitmap. ... Return image as a bytes object. ... This method returns raw image data derived from Pillow’s internal storage. For compressed image data (e.g.
🌐
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 - In this post, I will share how to convert Numpy image or PIL Image object to binary data without saving the underlying image to disk. If the image file is saved on disk, we can read it directly in binary format with open() method by using the b flag: with open('test.jpg', 'rb') as f: byte_im = f.read()
🌐
GitHub
gist.github.com › sleepless-se › 3674830cbb53b9e04b03b18f2b47815e
PIL image convert to byte array · GitHub
PIL image convert to byte array. GitHub Gist: instantly share code, notes, and snippets.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pil-tobytes-method
Python PIL | tobytes() Method - GeeksforGeeks
August 2, 2019 - 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:
🌐
MyCleverAI
mycleverai.com › it-questions › how-do-i-convert-a-pil-image-to-bytes
How do I convert a PIL image to bytes?
2. Create an In-Memory Byte Stream: Use io.BytesIO() to create an in-memory byte stream. 3. Save the PIL Image to the Byte Stream: Use the save() method of the PIL Image object to save the image to the byte stream, specifying the format (e.g., 'JPEG', 'PNG').
Find elsewhere
🌐
Pillow
pillow.readthedocs.io › en › latest › _modules › PIL › Image.html
PIL.Image - Pillow (PIL Fork) 13.0.0.dev0 documentation
[docs] def tobytes(self, encoder_name: str = "raw", *args: Any) -> bytes: """ Return image as a bytes object. .. warning:: This method returns raw image data derived from Pillow's internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data.
🌐
Reddit
reddit.com › r/learnpython › pil image to bytes and saving it as jpg is not working
r/learnpython on Reddit: PIL Image to bytes and saving it as jpg is not working
January 16, 2020 -

I need to make a image to thumbnail and upload it to dropbox so I need to send it as Bytes, but it is not working So to recreate the problem

from PIL import Image

img = Image.open("test.jpg")
img.thumbnail((128,128), Image.ANTIALIAS)

bytes = img.tobytes()
#These bytes are send to the dropbox

f = open("128.jpg", "wb")
f.write(bytes)
f.close()

And I can't open the image.

What am I missing here?

Thanks in Advance

🌐
Codecademy
codecademy.com › docs › python:pillow › image module › .frombytes()
Python:Pillow | Image Module | .frombytes() | Codecademy
March 21, 2025 - The .frombytes() method in Pillow creates an image from raw byte data. It reconstructs an image using a specified mode, size, and optional decoder arguments. This method is useful when working with raw image data that needs to be converted into ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pil-image-frombytes-method
Python PIL | Image.frombytes() Method - GeeksforGeeks
August 7, 2019 - [120, 100, 56, 225, 183, 235] Another Example: Here we use different raw in tobytes. ... # importing image object from PIL from PIL import Image # using tobytes data as raw for frombyte function tobytes = b'\xbf\x8cd\xba\x7f\xe0\xf0\xb8t\xfe' img = Image.frombytes("L", (3, 2), tobytes) # creating list img1 = list(img.getdata()) print(img1)
🌐
TechndSoft
techndsoft.com › how-to-convert-a-pil-image-to-bytes
How to Convert a PIL Image to Bytes
January 8, 2025 - Make a BytesIO object. Save your image to the object by using the Pillow’s `.save()Method.
🌐
Pillow Documentation
pillow.readthedocs.io › en › stable › _modules › PIL › Image.html
PIL.Image - Pillow (PIL Fork) 12.3.0 documentation
[docs] def tobytes(self, encoder_name: str = "raw", *args: Any) -> bytes: """ Return image as a bytes object. .. warning:: This method returns raw image data derived from Pillow's internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data.
🌐
sqlpey
sqlpey.com › python › solved-how-to-convert-pil-image-to-byte-array
Solved: How to Convert PIL Image to Byte Array Efficiently - …
November 23, 2024 - This method is useful when you want to obtain the byte representation of an image file already stored on disk. Using a Library Like OpenCV: OpenCV also offers methods to manipulate images which might suit certain workflows better, especially if you’re dealing with video feeds or real-time image processing. Converting From Other Formats: Ensure you check the available formats in the PIL save method if you need specific byte formats like JPEG or BMP instead of PNG.
🌐
ProgramCreek
programcreek.com › python › example › 89944 › PIL.Image.frombytes
Python Examples of PIL.Image.frombytes
def save_to_disk(self, filename, format='.png'): """Save this image to disk (requires PIL installed).""" filename = _append_extension(filename, format) try: from PIL import Image as PImage except ImportError: raise RuntimeError( 'cannot import PIL, make sure pillow package is installed') image = PImage.frombytes( mode='RGBA', size=(self.width, self.height), data=self.raw_data, decoder_name='raw') color = image.split() image = PImage.merge("RGB", color[2::-1]) folder = os.path.dirname(filename) if not os.path.isdir(folder): os.makedirs(folder) image.save(filename, quality=100) ... def __process
🌐
Stack Overflow
stackoverflow.com › questions › 32908639 › open-pil-image-from-byte-file
python - Open PIL image from byte file - Stack Overflow
I have this image with size 128 x 128 pixels and RGBA stored as byte values in my memory. But from PIL import Image image_data = ... # byte values of the image image = Image.frombytes('RGBA', (12...