Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, how can I asynchronously save the PIL images?

For asynchronous file saving, I can use aiofiles library.

To use aiofiles library I'd have to do something like that:

async with aiofiles.open(path, "wb") as file:
   await file.write(data)

How can I asynchronously save the PIL images? Even if I use Image.tobytes function to save it with file.write(data), the saved image isn't correct.

So how can I asynchronously save a PIL image?

like image 996
Karol Avatar asked Sep 06 '25 02:09

Karol


1 Answers

Thanks to the comment posted by @MarkSetchell I managed to find the solution.

async def save_image(path: str, image: memoryview) -> None:
    async with aiofiles.open(path, "wb") as file:
        await file.write(image)


image = Image.open(...)
buffer = BytesIO()
image.save(buffer, format="JPEG")

await save_image('./some/path', buffer.getbuffer())

I don't know how much speed one can gain, but in my case, I'm able to run some data processing code, data downloading code, and image saving code concurrently which gives me a speed up.

like image 186
Karol Avatar answered Sep 09 '25 20:09

Karol