使用 PIL 将图像路径更改为图像对象

Har*_*rry 0 python python-imaging-library

我正在使用自定义保存功能将图像路径保存到我的模型图像字段。然后我意识到我只是在保存路径而不是实际对象。我的问题是如何使用 PIL 将该路径转换为对象。

p8u*_*8ul 6

要将图像路径更改为 PIL 对象,您必须向图像路径发出请求,然后将内容转换为 BytesIO 并使用 PIL.Image 函数打开它。

import requests
from PIL import Image
from io import BytesIO

image_url = "https://recruiterflow.com/blog/wp-content/uploads/2017/10/stackoverflow.png"
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
output = BytesIO()
img.save(output, format='PNG')
Run Code Online (Sandbox Code Playgroud)