将医院给的在线CT查阅链接中提取为本地DICOM文件

719 阅读2分钟

由于家人生病的原因,需要经常在好大夫之类的在线问诊,这个时候要上传CT文件。要是以前,只能去医院求,大部分也不会给。还好,现在基本上大医院都会提供在线阅片,有的提供直接下载,有的不提供。但是这个在线阅片不太方便,而且有期限,所以想着抓包下载。

实施起来又遇到了困难,好多医院都是微信公众号上提供,不是网页。还好有找到调试手机微信的方式,可以用chrome调试,将所有流量数据转换为HAR。

然后又想到将HAR中的数据提取出来,将其中的DICOM格式的文件打包在一起,不就是DICOM了吗?哈哈,我是多么的天才,但是技术不行。怎么办?还好现在又chatgpt,我一步一步的问了几十个问题,终于写出来这个代码,附在最后供大家参考。

HAR文件中的内容文本(text)通常以Base64编码的形式存储。因此,如果要提取其中的数据,您需要先进行Base64解码,然后再进行后续处理,例如保存为DICOM文件。

在之前的代码中,我们使用了base64.b64decode()函数对HAR文件中的内容文本进行解码,以获取原始的DICOM数据。解码后的数据可以用于验证是否为有效的DICOM文件,并进一步保存或处理。

需要注意的是,并非所有HAR文件的内容文本都是以Base64编码形式存储的。有时候,内容文本可能是原始的二进制数据或其他编码方式。因此,根据实际情况,您可能需要对解码方式进行适当的调整。

HAR文件: blog.csdn.net/csucsgoat/a…

如何用电脑调试手机的微信: www.52pojie.cn/thread-1826…

import json
import base64
import pydicom
import binascii
import os
from io import BytesIO
from datetime import datetime

def check_har_for_dicom(har_file_path, save_folder):
    with open(har_file_path, 'r', encoding='utf-8') as file:
        har_data = json.load(file)

    subfolder = create_subfolder(save_folder)

    count = 1

    for entry in har_data['log']['entries']:
        response = entry['response']
        content = response.get('content', {})
        text = content.get('text')

        if text:
            try:
                decoded_data = base64.b64decode(text.encode('utf-8'))
            except binascii.Error:
                print("Invalid Base64 encoding!")
                continue

            if is_valid_dicom(decoded_data):
                save_dicom_file(decoded_data, subfolder, count)
                count += 1

def create_subfolder(save_folder):
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    subfolder = os.path.join(save_folder, 'data_folder', timestamp)
    os.makedirs(subfolder, exist_ok=True)
    return subfolder

def is_valid_dicom(content):
    try:
        file_like = BytesIO(content)
        pydicom.dcmread(file_like)
        return True
    except pydicom.errors.InvalidDicomError:
        return False

def save_dicom_file(content, subfolder, count):
    file_name = f"dicom_file_{count}.dcm"
    file_path = os.path.join(subfolder, file_name)
    with open(file_path, 'wb') as file:
        file.write(content)

    print(f"Saved DICOM file: {file_path}")

# Provide the HAR file path and save folder
har_file_path = r'xx\Downloads\imagecloud.shca.org.cn.har'
save_folder = r'xx\Downloads'

# Check HAR file for DICOM content and save the DICOM files
check_har_for_dicom(har_file_path, save_folder)