我向Dicom服务器发出Get请求,该服务器返回Multipart / Related Type = image / jpeg。我尝试使用aiohttp libararies Multipart功能来解析,但是没有用。保存的文件已损坏。
这是我的代码。
import asyncio
import aiohttp
'''
async def fetch(url,session,header):
async with session.get(url,headers=header) as response:
await response
async def multiHit(urls,header):
tasks = []
async with aiohttp.ClientSession() as session:
for i,url in enumerate(urls):
tasks.append(fetch(url,session,header))
result = await asyncio.gather(*tasks)
return result
loop = asyncio.get_event_loop()
res = loop.run_until_complete(multiHit(["http://10.177.216.224/ea/AE_ARCH1/studies/1.2.528.1.1001.100.2.4237.5261.110511058.20131122121300514/series/1.2.528.1.1001.100.3.4237.5261.110511058.20131122121300530/instances/1.2.528.1.1001.100.4.4237.5261.110511058.20131122121300546/frames/1"],{"Accept":"multipart/related;type=image/jpeg"}))
print(res)
'''
async def xyz(loop):
async with aiohttp.ClientSession(loop=loop).get(url="http://10.177.216.224/ea/AE_ARCH1/studies/1.2.528.1.1001.100.2.4237.5261.110511058.20131122121300514/series/1.2.528.1.1001.100.3.4237.5261.110511058.20131122121300530/instances/1.2.528.1.1001.100.4.4237.5261.110511058.20131122121300546/frames/1",headers={"Accept":"multipart/related;type=image/jpeg"}) as response:
reader = aiohttp.MultipartReader.from_response(response)
while True:
part = await reader.next()
if part is None:
break
filedata = await part.read(decode=False)
import base64
with open('m.jpeg','wb') as outFile:
outFile.write(part.decode(filedata))
return 1
loop = asyncio.get_event_loop()
res = loop.run_until_complete(xyz(loop))
如何解析多部分/相关响应并保存图像?
我发现我正在正确解析多部分响应,但是我不得不使用另一个库(库名:imagecodecs,方法名:jpegsof3_decode)将单个部分解压缩到图像中。这给出了图像的numpy数组。这是更新的代码
reader = aiohttp.MultipartReader.from_response(response)
while True:
part = await reader.next()
if part is None:
break
data = await part.read()
imageDecompressed = jpegsof3_decode(data)
此外,可以使用cv2 libray将numpy数组转换为图像
success, encoded_image = cv2.imencode('.png',imageDecompressed)
可以通过这种方式获得转换后图像的字节版本
imageInBytes = encoded_image.tobytes()