![](/img/trans.png)
[英]How can I save lots of images after resizing them all into another directory in Python(PIL)?
[英]Python, how can I asynchronously save the PIL images?
對於異步文件保存,我可以使用aiofiles
庫。
要使用aiofiles
庫,我必須這樣做:
async with aiofiles.open(path, "wb") as file:
await file.write(data)
如何異步保存 PIL 圖像? 即使我使用Image.tobytes
function 用file.write(data)
保存它,保存的圖像也不正確。
那么如何異步保存 PIL 圖像呢?
感謝@MarkSetchell 發表的評論,我設法找到了解決方案。
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())
我不知道一個人可以獲得多少速度,但就我而言,我能夠同時運行一些數據處理代碼、數據下載代碼和圖像保存代碼,這讓我加快了速度。
@CrazyChucky,感謝您指出異步同步。 我再次為此工作
from fastapi import File,UploadFile
from PIL import Image,ImageFont, ImageDraw
from io import BytesIO
@router.post("/users/update_user_profile")
async def upload_file(self, image_file : UploadFile = File(None)):
out_image_name = 'image_name'+pathlib.Path(image_file.filename).suffix
out_image_path = f"images/user/{out_image_name}"
request_object_content = await image_file.read()
photo = Image.open(BytesIO(request_object_content))
# make the image editable
drawing = ImageDraw.Draw(photo)
black = (3, 8, 12)
drawing.text((0,0), 'Your_text', fill=black)#, font=font)
# Create a buffer to hold the bytes
buf = BytesIO()
# Save the image as jpeg to the buffer
photo.save(buf, format='JPEG')#
async with aiofiles.open(out_image_path, 'wb') as out_file:
outContent = await out_file.write(buf.getbuffer()) # async write
return out_image_name
我提到了@Karol 的建議。 現在檢查,這是用於 fastapi 異步方法的
就我而言,以下工作(使用 python fastapi)
from fastapi import File,UploadFile
from PIL import Image,ImageFont, ImageDraw
from io import BytesIO
async def upload_file(image_file : UploadFile = File(None)):
out_image_name = str(123)+pathlib.Path(image_file.filename).suffix
out_image_path = f"images/user/{out_image_name}"
request_object_content = await image_file.read()
photo = Image.open(BytesIO(request_object_content))
# make the image editable
drawing = ImageDraw.Draw(photo)
black = (3, 8, 12)
# font = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 40)
drawing.text((0,0), 'text_to_water_mark', fill=black)#, font=font)
photo.save(out_image_path)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.