Python,如何异步保存PIL图像?

Kar*_*rol 4 python python-imaging-library

对于异步文件保存,我可以使用aiofiles库。

要使用aiofiles库我必须做类似的事情:

async with aiofiles.open(path, "wb") as file:
   await file.write(data)
Run Code Online (Sandbox Code Playgroud)

如何异步保存PIL图像?即使我使用Image.tobytes函数保存它file.write(data),保存的图像也不正确。

那么如何异步保存PIL图像呢?

Kar*_*rol 8

感谢@MarkSetcell 发表的评论,我设法找到了解决方案。

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())
Run Code Online (Sandbox Code Playgroud)

我不知道可以获得多少速度,但就我而言,我能够同时运行一些数据处理代码、数据下载代码和图像保存代码,这给我带来了加速。