Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert PIL Image object to File object

Is there any way (without saving a file to disk and then deleting it) to convert a PIL Image object to a File object?

like image 273
KelluvaKobra Avatar asked Oct 05 '17 19:10

KelluvaKobra


1 Answers

Let's look at what a file object is.

with open('test.txt', 'r') as fp:
    print(fp)
    # <_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'>

https://docs.python.org/3/library/io.html has more on the subject as well.

I suspect that for your purposes, it would be enough to have a BytesIO object.

import io
from PIL import Image
im = Image.new("RGB", (100, 100))
b = io.BytesIO()
im.save(b, "JPEG")
b.seek(0)

But if you really want the same object, then -

fp = io.TextIOWrapper(b)
like image 154
radarhere Avatar answered Oct 21 '22 16:10

radarhere