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

时间:2010-08-30 11:40:15

标签: python python-imaging-library

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

3 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

  

如何使用PIL将该路径转换为对象

如果对象是指使用PIL读取图像,则可以执行以下操作:

from PIL import Image
image = Image.open(<path>)

我不知道你的意思如何。

答案 2 :(得分:0)

你的意思是这样的:

import urllib, Image
image = urllib.URLopener()
cookie = 'PHPSESSID=4a52...'
image.addheader('Cookie',cookie)
image.retrieve("http://www.your-domain.net/NASA.png", "NASA.png")
im = Image.open("NASA.png")
im.show()
相关问题