convert PIL Image object to File object

Viewed 7181

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

2 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)

Use a temporary file from the tempfile standard library.

from tempfile import TemporaryFile
from PIL import Image

fp = TemporaryFile()

img = Image.new("RGB", (100, 100))
img.save(fp, "PNG")

Don't forget to reset the position!

fp.seek(0)

Closing the file will remove it

fp.close()

https://docs.python.org/3/library/tempfile.html

Related