对于异步文件保存,我可以使用库。
要使用库,我需要像这样做:
async with aiofiles.open(path, "wb") as file:
await file.write(data)
我怎样才能异步地保存PIL图像?即使我使用
Image.tobytes
函数并用file.write(data)
保存它,保存的图像也不正确。那么我该怎样异步保存PIL图像?对于异步文件保存,我可以使用库。
要使用库,我需要像这样做:
async with aiofiles.open(path, "wb") as file:
await file.write(data)
Image.tobytes
函数并用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 异步方法的。
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)
JPEG
)传递给您在问题中提到的file.write()
。请参见https://dev59.com/SW0NtIcB2Jgan1znExGf#70275120。 - Mark Setchell