Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Engines/ImageProcessing/CardImageCodec.swift8// Module : SPVault9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CoreGraphics42import CoreImage43import Foundation44import ImageIO45import UniformTypeIdentifiers4647enum CardImageCodecError: Error { case encodingFailed, decodingFailed }4849/// Turns a processed card photograph into the bytes the vault encrypts. Images50/// are re-encoded from pixels, so no camera metadata (EXIF, GPS, maker notes)51/// ever reaches the vault. Everything happens in memory.52enum CardImageCodec {53 /// Long edge of the stored photograph, in pixels. Enough for a full-screen54 /// zoom on a 3× display without keeping a 48 MP original.55 static let fullLongEdge = 240056 static let thumbnailLongEdge = 9005758 static func encode(_ image: CGImage, quality: Double = 0.9) throws -> Data {59 for type in [UTType.heic, UTType.jpeg] {60 let data = NSMutableData()61 guard let destination = CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil) else { continue }62 CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)63 if CGImageDestinationFinalize(destination), data.length > 0 { return data as Data }64 }65 throw CardImageCodecError.encodingFailed66 }6768 static func decode(_ data: Data) throws -> CGImage {69 guard let source = CGImageSourceCreateWithData(data as CFData, nil),70 let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw CardImageCodecError.decodingFailed }71 return image72 }7374 /// Scales down (never up) so the long edge is at most `longEdge`.75 static func resized(_ image: CGImage, longEdge: Int) -> CGImage {76 let current = max(image.width, image.height)77 guard current > longEdge else { return image }78 let scale = Double(longEdge) / Double(current)79 let width = max(1, Int((Double(image.width) * scale).rounded())), height = max(1, Int((Double(image.height) * scale).rounded()))80 guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,81 space: CGColorSpace(name: CGColorSpace.sRGB)!,82 bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return image }83 context.interpolationQuality = .high84 context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))85 return context.makeImage() ?? image86 }8788 /// Full image + thumbnail for each side, ready for `Vault.add`.89 static func images(front: CGImage, back: CGImage?) throws -> CardImages {90 func pair(_ image: CGImage) throws -> (Data, Data) {91 (try encode(resized(image, longEdge: fullLongEdge)),92 try encode(resized(image, longEdge: thumbnailLongEdge), quality: 0.82))93 }94 let (frontData, frontThumb) = try pair(front)95 let backPair = try back.map(pair)96 return CardImages(front: frontData, frontThumbnail: frontThumb, back: backPair?.0, backThumbnail: backPair?.1)97 }9899 /// Average colour of the photograph (Core Image `CIAreaAverage`).100 static func dominantColor(of image: CGImage) -> RGB {101 let input = CIImage(cgImage: image)102 guard let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: input,103 kCIInputExtentKey: CIVector(cgRect: input.extent)]),104 let output = filter.outputImage else { return .titanium }105 var pixel = [UInt8](repeating: 0, count: 4)106 let context = CIContext(options: [.workingColorSpace: NSNull()])107 context.render(output, toBitmap: &pixel, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1),108 format: .RGBA8, colorSpace: CGColorSpace(name: CGColorSpace.sRGB))109 return RGB(r: Double(pixel[0]) / 255, g: Double(pixel[1]) / 255, b: Double(pixel[2]) / 255)110 }111}112