Moderne gezondheidszorg toepassingen worden steeds meer gebaseerd op webgebaseerde interfaces voor het bekijken en beheren van medische beeldgegevens. Converting DICOM-bestanden naar JSON zorgt voor onbeperkte integratie met JavaScript-frames, REST-API’s en cloudplatforms. Deze gids laat je zien hoe je DIKOM naar C# kunt converteren met behulp van Aspose.Medical voor .NET.

Waarom DICOM om te zetten in JSON?

DICOM (Digital Imaging and Communications in Medicine) is het standaardformaat voor medische afbeelding, maar de binaire structuur maakt het uitdagend om te werken met in web-applicaties.

  • JavaScript compatibiliteit: JSON is native to web browsers en frontend frameworks zoals React, Vue en Angular
  • REST API integratie: JSON is de de facto standaard voor moderne web API’s
  • Database opslag: NoSQL-databases zoals MongoDB opslaan JSON-documenten natively
  • Human readability: JSON is gemakkelijk te inspecteren en af te vullen in vergelijking met binaire DICOM

De DICOM PS3.18-standaard definieert een JSON-representatie voor Dicom-gegevens, waardoor de interoperabiliteit tussen gezondheidszorgsystemen wordt gewaarborgd.

Installeer uw .NET project

Installeer eerst Aspose.Medical voor .NET en configureer gemeten licentie:

using Aspose.Medical;
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

// Activate metered license
Metered metered = new Metered();
metered.SetMeteredKey("your-public-key", "your-private-key");

Basic DICOM naar JSON Conversie

De eenvoudigste manier om een DICOM-bestand naar JSON te converteren:

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

public class DicomJsonConverter
{
    public string ConvertToJson(string dicomFilePath)
    {
        // Load the DICOM file
        DicomFile dicomFile = DicomFile.Open(dicomFilePath);
        
        // Serialize dataset to JSON string
        string json = DicomJsonSerializer.Serialize(dicomFile.Dataset);
        
        return json;
    }
}

Pretty-Print JSON voor Debugging

Tijdens de ontwikkeling is geformateerd JSON makkelijker om te lezen en te debuggen:

public string ConvertToFormattedJson(string dicomFilePath)
{
    DicomFile dicomFile = DicomFile.Open(dicomFilePath);
    
    // Configure serialization options
    var options = new DicomJsonSerializerOptions
    {
        WriteIndented = true  // Enable pretty-print
    };
    
    string json = DicomJsonSerializer.Serialize(dicomFile.Dataset, options);
    
    return json;
}

Keywords gebruiken in plaats van hex codes

Door standaard, DICOM JSON gebruikt hexadecimal tag codes. Voor meer leesbare output, gebruik de keyword namen:

public string ConvertWithKeywords(string dicomFilePath)
{
    DicomFile dicomFile = DicomFile.Open(dicomFilePath);
    
    var options = new DicomJsonSerializerOptions
    {
        WriteIndented = true,
        UseKeywordsAsJsonKeys = true,  // Use "PatientName" instead of "00100010"
        WriteKeyword = true,           // Include keyword in output
        WriteName = true               // Include human-readable name
    };
    
    string json = DicomJsonSerializer.Serialize(dicomFile.Dataset, options);
    
    return json;
}

Het bouwen van een REST API Endpoint

Hier is hoe u een ASP.NET Core-endpoint kunt maken die de gedownload DICOM-bestanden converteert naar JSON:

using Microsoft.AspNetCore.Mvc;
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

[ApiController]
[Route("api/[controller]")]
public class DicomController : ControllerBase
{
    [HttpPost("to-json")]
    public async Task<IActionResult> ConvertToJson(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            return BadRequest("No DICOM file provided");
        }

        try
        {
            // Save uploaded file temporarily
            var tempPath = Path.GetTempFileName();
            using (var stream = new FileStream(tempPath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            // Convert to JSON
            DicomFile dicomFile = DicomFile.Open(tempPath);
            
            var options = new DicomJsonSerializerOptions
            {
                WriteIndented = true,
                UseKeywordsAsJsonKeys = true
            };
            
            string json = DicomJsonSerializer.Serialize(dicomFile.Dataset, options);

            // Clean up temp file
            System.IO.File.Delete(tempPath);

            return Content(json, "application/json");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Conversion failed: {ex.Message}");
        }
    }
    
    [HttpGet("metadata/{fileName}")]
    public IActionResult GetMetadata(string fileName)
    {
        var filePath = Path.Combine("DicomFiles", fileName);
        
        if (!System.IO.File.Exists(filePath))
        {
            return NotFound("DICOM file not found");
        }

        DicomFile dicomFile = DicomFile.Open(filePath);
        
        // Extract specific metadata fields
        var metadata = new
        {
            PatientName = dicomFile.Dataset.GetString(DicomTag.PatientName),
            PatientID = dicomFile.Dataset.GetString(DicomTag.PatientID),
            StudyDate = dicomFile.Dataset.GetString(DicomTag.StudyDate),
            Modality = dicomFile.Dataset.GetString(DicomTag.Modality),
            StudyDescription = dicomFile.Dataset.GetString(DicomTag.StudyDescription)
        };

        return Ok(metadata);
    }
}

Stream-gebaseerde serialisatie voor grote bestanden

Voor grote DICOM-bestanden, gebruik stream-based serialisatie om het geheugengebruik te verminderen:

public async Task ConvertToJsonStreamAsync(string dicomFilePath, string outputPath)
{
    DicomFile dicomFile = DicomFile.Open(dicomFilePath);
    
    var options = new DicomJsonSerializerOptions
    {
        WriteIndented = true
    };
    
    using (var fileStream = new FileStream(outputPath, FileMode.Create))
    {
        await DicomJsonSerializer.SerializeAsync(
            fileStream, 
            dicomFile.Dataset, 
            options);
    }
}

Batch Conversie voor meerdere bestanden

Verwerking van volledige directories van DICOM-bestanden:

public class BatchDicomConverter
{
    public async Task ConvertDirectoryAsync(string inputDir, string outputDir)
    {
        Directory.CreateDirectory(outputDir);
        
        var dicomFiles = Directory.GetFiles(inputDir, "*.dcm");
        
        var options = new DicomJsonSerializerOptions
        {
            WriteIndented = true,
            UseKeywordsAsJsonKeys = true
        };

        foreach (var filePath in dicomFiles)
        {
            try
            {
                DicomFile dicomFile = DicomFile.Open(filePath);
                
                string fileName = Path.GetFileNameWithoutExtension(filePath);
                string outputPath = Path.Combine(outputDir, $"{fileName}.json");
                
                using (var stream = new FileStream(outputPath, FileMode.Create))
                {
                    await DicomJsonSerializer.SerializeAsync(
                        stream, 
                        dicomFile.Dataset, 
                        options);
                }
                
                Console.WriteLine($"Converted: {fileName}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to convert {filePath}: {ex.Message}");
            }
        }
    }
}

Integratie met React Frontend

Zodra uw API JSON terugkomt, is het consumeren in React eenvoudig:

// React component to display DICOM metadata
import React, { useState } from 'react';

function DicomViewer() {
    const [metadata, setMetadata] = useState(null);
    
    const handleFileUpload = async (event) => {
        const file = event.target.files[0];
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('/api/dicom/to-json', {
            method: 'POST',
            body: formData
        });
        
        const json = await response.json();
        setMetadata(json);
    };
    
    return (
        <div>
            <input type="file" onChange={handleFileUpload} accept=".dcm" />
            {metadata && (
                <pre>{JSON.stringify(metadata, null, 2)}</pre>
            )}
        </div>
    );
}

Beste praktijken

Bij het omzetten van DICOM naar JSON voor webtoepassingen, houd deze tips in gedachten:

  • Anoniem voor het converteren: Altijd patiënt identificerbare informatie verwijderen voordat DICOM-gegevens worden blootgesteld via web-API’s
  • ** Gebruik async methoden**: Voor webtoepassingen, gebruik assynchronous serialisatie om te voorkomen dat banden worden geblokkeerd
  • Cache converteerde gegevens: Als dezelfde DICOM-bestanden vaak worden gevraagd, cacheert u de JSON-uitgang
  • Valideer inputbestanden: Controleer dat de geüploaderde bestanden DICOM geldig zijn vóór verwerking
  • Binaire gegevens zorgvuldig verwerken: Grote pixelgegevens moeten gescheiden of uitgesloten worden van JSON-reacties

Conclusie

Het omzetten van DICOM-bestanden naar JSON opent medische beeldgegevens voor de moderne webontwikkeling. Met Aspose.Medical voor .NET kunt u gemakkelijk serialiseren datasets naar PS3.18-compliant json, REST APIs bouwen en integreren met JavaScript-frameworks. De voorbeelden in deze gids bieden een basis voor het opbouwen van webgebaseerde DIKOM kijkers, patiëntenportaals en gezondheids-gegevensplatforms.

Voor meer informatie over DICOM JSON serialisatie opties, bezoek de Aspose.Medische documentatie.

More in this category