【发布时间】:2022-01-26 12:22:10
【问题描述】:
我要检查 (image_file) 变量格式
并验证它是“.png”还是“.jpg”。
image_str = urlopen(url).read()
image_file = io.BytesIO(image_str)
url 是来自 reddit 的随机文件。
【问题讨论】:
我要检查 (image_file) 变量格式
并验证它是“.png”还是“.jpg”。
image_str = urlopen(url).read()
image_file = io.BytesIO(image_str)
url 是来自 reddit 的随机文件。
【问题讨论】:
最好的库可能是imghdr,它检查图像并识别它们的文件类型:
import imghdr
imghdr.what("/path/to/file")
# OR...
imghdr.what("", h=io.BytesIO(imge_str))
【讨论】:
您可以使用endswith
在您的情况下,如果 url 是您文件中的字符串,您可以使用:
if url.endswith('.png'):
...
elif url.endswith('.jpg'):
...
【讨论】: