在 Python 中,我想将图像保存到文件中。文件名应该是哈希值,由imagehash.average_hash()
. 使用ls -l
I see files 但它们是空的:
-rw-r--r-- 1 lorem lorem 0 8 Sep 16:20 c4c0bcb49890bcfc.jpg
-rwxr-xr-x 1 lorem lorem 837 8 Sep 16:19 minimal.py
代码:
import requests
from PIL import Image
import imagehash
import shutil
def safe_to_file(url):
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}
image_hash = ''
r = requests.get(url, headers=headers, timeout=10, stream=True)
try:
if r.status_code == 200:
image_hash = str(imagehash.average_hash(Image.open(r.raw))) + '.jpg'
print(image_hash)
with open(image_hash, 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
except Exception as ex:
print(str(ex))
finally:
return image_hash
# Random jpg picture
url = 'https://cdn.ebaumsworld.com/mediaFiles/picture/1035099/85708057.jpg'
safe_to_file(url)
我希望图像不为空。我究竟做错了什么?