import Foundation enum DICOMCodec { static func normalized(from source: URL, applyPalette: Bool = false) throws -> Data { let decoder = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/gdcmconv") guard FileManager.default.isExecutableFile(atPath: decoder.path) else { throw DICOMError.transferSyntax } let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) defer { try? FileManager.default.removeItem(at: folder) } let decoded = folder.appendingPathComponent("decoded.dcm") let process = Process() process.executableURL = decoder process.arguments = (applyPalette ? ["--apply-lut8"] : ["--raw", "--explicit"]) + ["-i", source.path, "-o", decoded.path] process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevice try process.run() process.waitUntilExit() guard process.terminationReason == .exit, process.terminationStatus == 0 else { throw DICOMError.transferSyntax } return try Data(contentsOf: decoded, options: .mappedIfSafe) } }