Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file object from raw binary information in Python

Question

What is a clean way to create a file object from raw binary information in Python?

More Info

The reason I need to do this is because I have the raw binary information comprising a jpeg image stored in ram. I need to put it inside some kind of file object so that I can resize the image using Python's Pillow library.

According to the pillow documentation, the file object needs to implement the read(), seek(), and tell() methods.

The file object must implement read(), seek(), and tell() methods, and be opened in binary mode.
like image 779
Chris Dutrow Avatar asked Sep 29 '26 05:09

Chris Dutrow


1 Answers

I was able to find a mention of how to handle this situation under the documentation for PIL.Image.frombytes:

...If you have an entire image in a string, wrap it in a BytesIO object,
 and use open() to load it.

This is what I ended up with that worked using BytesIO:

import io
import PIL
from PIL.Image import Image

file_body = <binary image data>
t_file = io.BytesIO(file_body)
img    = PIL.Image.open(t_file)

Note: The comments mention tempfile.SpooledTemporaryFile. This seems like it should have worked, but it did not for some reason.

like image 114
Chris Dutrow Avatar answered Oct 01 '26 17:10

Chris Dutrow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!