简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM