我需要计算从CDN服务器下载的镜像的哈希值.使用同步库时,一切都运行得很好.我直接将请求的结果(Res)传递给Image.open(),并接收一个带有图像作为输出的对象(Img).
import requests
import imagehash
from PIL import Image
# sync
def get_picture():
url = 'https://ae01.alicdn.com/kf/Sec174725eb944b4693342178da975d52z.jpg'
res = requests.get(url, stream=True).raw
img = Image.open(res)
hash = imagehash.phash(img, hash_size=6)
print(f'hash: {hash}')
但是我需要判断很多照片,并且需要异步执行请求,在这里我遇到了一个问题,因为我不能直接将带有图像的请求对象传输到Image.Open(),只有首先将其保存到文件,但这个选项不适合我(我不需要服务器上的文件).
import imagehash
from PIL import Image
from aiohttp import ClientSession
from config.settings import BASE_DIR
# async
async def get_aio_picture():
url = 'https://ae01.alicdn.com/kf/Sec174725eb944b4693342178da975d52z.jpg'
async with ClientSession() as session:
async with session.get(url=url) as response:
response.auto_decompress = False
with open('picture.jpg', 'wb') as fd:
async for line in response.content:
fd.write(line)
img = Image.open(f'{BASE_DIR}/picture.jpg')
hash = imagehash.phash(img, hash_size=6)
print(f'hash: {hash}')
async def main():
task = asyncio.create_task(get_aio_picture())
await task
def aio_hash():
asyncio.run(main())
如果我以直接将结果传递给Image.open()的方式更改函数代码:
async def get_aio_picture():
url = 'https://ae01.alicdn.com/kf/Sec174725eb944b4693342178da975d52z.jpg'
async with ClientSession() as session:
async with session.get(url=url) as response:
response.auto_decompress = False
async for line in response.content:
img = Image.open(line)
hash = imagehash.phash(img, hash_size=6)
print(f'hash: {hash}')
然后我得到错误:(
...
File "/home/.../main/services/aio/help.py", line 37, in get_aio_picture
img = Image.open(line)
File "/home/.../env/lib/python3.10/site-packages/PIL/Image.py", line 3247, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte
如何更改代码以避免在磁盘上创建文件? 帮帮我!