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

python - Open PIL image from byte file - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... 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 = ... More on stackoverflow.com
🌐 stackoverflow.com
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 - 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 ... If you manipulate with bytearrays, then you have to use io.BytesIO. Also you can read a file directly to a bytearray. import os import io import PIL.Image as Image ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - Gist - GitHub
PIL image convert to byte array. GitHub Gist: instantly share code, notes, and snippets.
🌐
MyCleverAI
mycleverai.com › it-questions › how-do-i-convert-a-pil-image-to-bytes
How do I convert a PIL image to bytes?
4. Retrieve the Bytes: Get the bytes from the byte stream using the getvalue() method. ... from PIL import Image import io # Assuming you have a PIL Image object named 'image' def pil_image_to_byte_array(image: Image) -> bytes: img_byte_arr = io.BytesIO() image.save(img_byte_arr, format='PNG') ...
🌐
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)
🌐
GeeksforGeeks
geeksforgeeks.org › 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:
Find elsewhere
🌐
YouTube
youtube.com › how to fix your computer
PYTHON : Convert PIL Image to byte array? - YouTube
PYTHON : Convert PIL Image to byte array? [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON : Convert PIL Image to byte ar...
Published   December 8, 2021
Views   845
🌐
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

🌐
Pillow Documentation
pillow.readthedocs.io › en › stable › _modules › PIL › Image.html
PIL.Image - Pillow (PIL Fork) 12.2.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.
🌐
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 › 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.
🌐
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 ...
🌐
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.
🌐
ProgramCreek
programcreek.com › python › example › 89944 › PIL.Image.frombytes
Python Examples of PIL.Image.frombytes
def screen_game(region, save_to=None): x, y, width, height = region try: raw = root.get_image(x, y, width, height, X.ZPixmap, 0xffffffff) if hasattr(Image, 'frombytes'): # for Pillow screenshot = Image.frombytes('RGB', (width, height), raw.data, 'raw', 'BGRX') else: # for PIL screenshot = Image.fromstring('RGB', (width, height), raw.data, 'raw', 'BGRX') if save_to is not None: screenshot.save(save_to + '.png') except: filename = save_to + '.png' if save_to is not None else None screenshot = pyautogui.screenshot(filename, region) return screenshot # Return pixel color of given x, y coordinates
🌐
Bitbucket
hhsprings.bitbucket.io › docs › programming › examples › python › PIL › Image__Functions.html
Image Module - Functions — Pillow (PIL) examples - bitbucket.io
>>> # example for single band >>> from PIL import Image >>> >>> rawpb = bytearray(b'\x00\x01\x02\x03\x04\x05') >>> >>> # >>> img = Image.frombuffer("L", (3, 2), rawpb, 'raw') # cause warning in Pillow 4.1.x. __console__:1: RuntimeWarning: the frombuffer defaults may change in a future release; for portability, change the call to read: frombuffer(mode, size, data, 'raw', mode, 0, 1) >>> # the above is identical to (in Pillow 4.1.x.): # may change in a future release >>> # img = Image.frombuffer("L", (3, 2), rawpb, 'raw', 0, -1) >>> list(img.getdata()) # data is imported with "bottom to top order" [3, 4, 5, 0, 1, 2] >>> >>> img.tobytes("raw") '\x03\x04\x05\x00\x01\x02' >>> >>> for y in range(2): ...