如何获取图像的图像大小并使用它来命名图像

How to get the image size of an image and use it to name the image

我需要从互联网上下载一张图片并根据其尺寸命名,例如 1920 x 1080。 我设法将图像下载到我的本地计算机,但我不确定在下载图像之前如何获取图像尺寸。 我在想也许我可以下载图片,使用 PIL 获取图片尺寸,重新下载图片,然后删除旧图片,但这需要更长的时间。

for landcover in data['results']:
  siteId = landcover['siteId']
  measuredDate = landcover['measuredDate']
  latitude = landcover['latitude']
  longitude = landcover['longitude']
  protocol = landcover['protocol']
  DownURL = landcover['data']['landcoversDownwardPhotoUrl']
  EastURL = landcover['data']['landcoversEastPhotoUrl']

  r = requests.get(EastURL)
  with open('GLOBEObserver_' + str(userid) + '_' + str(siteId) + '_' + protocol + '_' + str(latitude) + '_' + str(longitude) + '_' + str(measuredDate) + '_' + str(width) + '_' + str(height) + 'East.jpg', 'wb') as f:
    f.write(r.content)

其实步骤:

  1. 获取图片的字节数。
  2. 使用PIL将其(bytes)转换为PIL.Image(对象)。
  3. 获取对象的大小。
  4. 在本地保存对象

简单示例:

import requests
import io
import PIL

response = requests.get(url) # make sure it is the url of the image
image_bytes = response.content

# convert the bytes to image
image = Image.open(io.BytesIO(image_bytes))
width, height = image.size
# save it
image.save(f"{width}x{height}.jpg")