gpt4 book ai didi

python - 如何使用图像哈希作为下载图像的文件名?

转载 作者:行者123 更新时间:2023-12-04 17:33:10 25 4
gpt4 key购买 nike

在 Python 中,我想将图像保存到文件中。文件名应该是哈希值,由 imagehash.average_hash() 生成。使用 ls -l 我看到了文件,但它们是空的:

-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)

我希望图像不为空。我做错了什么?

最佳答案

正如我所怀疑的那样,PIL.Image 对象的创建会消耗并从 url 下载所有图像数据,因此 shutil.copyfileobj() 无需执行任何操作消费。

下面的代码似乎通过使用所需的基于哈希的文件名显式保存 Image 对象来避免该问题。我添加了注释以指示重大更改。

import imagehash
from PIL import Image
import requests
#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:
img = Image.open(r.raw) # ADDED
image_hash = str(imagehash.average_hash(img)) + '.jpg' # CHANGED.
print('saving image:', image_hash)
img.save(image_hash) # ADDED
# with open(image_hash, 'wb') as f: # REMOVED
# r.raw.decode_content = True # REMOVED
# shutil.copyfileobj(r.raw, f) # REMOVED
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)

c4c0bcb49890bcfc.jpg 它创建的文件:

image file created

关于python - 如何使用图像哈希作为下载图像的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57838316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com