详解如何在PIL中从URL中打开一个图像

  • Post category:Python

在PIL中,可以通过以下步骤从URL中打开一个图像:

  1. 导入PIL库
from PIL import Image
from io import BytesIO
import requests
  1. 使用requests库下载图像
url = 'https://example.com/image.jpg'
response = requests.get(url)
  1. 将响应写入内存中的缓冲区
img_bytes = BytesIO(response.content)
  1. 使用PIL的Image.open()函数从缓冲区中打开图像
img = Image.open(img_bytes)

完整代码示例1:从URL中打开一张图片并显示

from PIL import Image
from io import BytesIO
import requests

url = 'https://example.com/image.jpg'
response = requests.get(url)
img_bytes = BytesIO(response.content)
img = Image.open(img_bytes)

# 显示图片
img.show()

完整代码示例2:从URL中打开一张图片,对其进行裁剪并保存

from PIL import Image
from io import BytesIO
import requests

url = 'https://example.com/image.jpg'
response = requests.get(url)
img_bytes = BytesIO(response.content)
img = Image.open(img_bytes)

# 图片裁剪
cropped_img = img.crop((100, 100, 400, 400))

# 图片保存
cropped_img.save('cropped_image.jpg')