SPB Git

Repository Public

ImageUtilities.swift 9.7 KB 192 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Sources/MacLustrIdentityUI/ImageUtilities.swift10// Module           : MacLustrIdentityUI11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// In-memory image helpers. Nothing here writes to disk.89import CoreImage90import CoreVideo91import Foundation92import ImageIO93import UniformTypeIdentifiers94import MacLustrIdentityCore9596enum ImageUtilities {97    /// Longest side sent for a document. The service accepts up to 3600 px (12 MB): a licence barcode (PDF417) and the98    /// fine print need the full resolution of a still photo, so the image is downscaled only beyond that.99    static let documentMaxSide = 3600100    /// JPEG quality of a document image.101    static let documentQuality: CGFloat = 0.92102    /// Under this short side a document photo is likely too small for the barcode to be read: the person is warned.103    static let documentMinShortSide = 1000104    /// Largest upload accepted by the service for one document image.105    static let documentMaxBytes = 12 * 1024 * 1024106    /// Short side of a selfie frame (the service needs 320 px at least and a face about 90 px wide).107    static let selfieShortSide: CGFloat = 720108109    /// Decodes any image the system can read, applies its orientation, limits its size and re-encodes it as JPEG.110    /// Re-encoding also drops every metadata block (EXIF, GPS, maker notes).111    /// An image smaller than `maxSide` keeps its size (it is never enlarged).112    static func normalizedJPEG(from data: Data, maxSide: Int = documentMaxSide, quality: CGFloat = documentQuality, maxBytes: Int = documentMaxBytes) -> (jpeg: Data, image: CGImage)? {113        guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil }114        let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,115                                        kCGImageSourceThumbnailMaxPixelSize: maxSide, kCGImageSourceShouldCacheImmediately: true]116        guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary), var jpeg = jpegData(image, quality: quality) else { return nil }117        // A very detailed 3600 px photo can exceed the upload limit: lower the quality a little rather than the resolution.118        var q = quality119        while jpeg.count > maxBytes, q > 0.6 {120            q -= 0.07121            guard let smaller = jpegData(image, quality: q) else { break }122            jpeg = smaller123        }124        return (jpeg, image)125    }126127    /// True when a document image is likely too small for its barcode and fine print to be read.128    static func isLowResolutionDocument(width: Int, height: Int) -> Bool {129        min(width, height) < documentMinShortSide130    }131132    static func jpegData(_ image: CGImage, quality: CGFloat) -> Data? {133        let out = NSMutableData()134        guard let dest = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }135        CGImageDestinationAddImage(dest, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)136        return CGImageDestinationFinalize(dest) ? out as Data : nil137    }138139    /// Encodes a video frame as JPEG, downscaled so that its short side is at most `maxShortSide`.140    static func jpegData(from pixelBuffer: CVPixelBuffer, maxShortSide: CGFloat, quality: CGFloat, context: CIContext) -> Data? {141        var image = CIImage(cvPixelBuffer: pixelBuffer)142        let short = min(image.extent.width, image.extent.height)143        if short > maxShortSide {144            let s = maxShortSide / short145            image = image.transformed(by: CGAffineTransform(scaleX: s, y: s))146        }147        let space = CGColorSpace(name: CGColorSpace.sRGB)!148        return context.jpegRepresentation(of: image, colorSpace: space, options: [CIImageRepresentationOption(rawValue: kCGImageDestinationLossyCompressionQuality as String): quality])149    }150151    static func cgImage(from pixelBuffer: CVPixelBuffer, context: CIContext) -> CGImage? {152        let image = CIImage(cvPixelBuffer: pixelBuffer)153        return context.createCGImage(image, from: image.extent)154    }155156    /// A Core Image context that keeps nothing between renders.157    static func makeContext() -> CIContext {158        CIContext(options: [.cacheIntermediates: false])159    }160161    /// Luminance statistics of a video frame, sampled so that the long side is about 900 px (the scale used by the server).162    static func lumaQuality(of pixelBuffer: CVPixelBuffer) -> LumaQuality? {163        CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)164        defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }165        let format = CVPixelBufferGetPixelFormatType(pixelBuffer)166        if format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange || format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange {167            guard let base = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0) else { return nil }168            let w = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0), h = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0), row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0)169            let buffer = UnsafeBufferPointer(start: base.assumingMemoryBound(to: UInt8.self), count: row * h)170            return LumaQuality.measure(luma: buffer, width: w, height: h, bytesPerRow: row, step: max(1, max(w, h) / 900))171        }172        if format == kCVPixelFormatType_32BGRA {173            guard let base = CVPixelBufferGetBaseAddress(pixelBuffer) else { return nil }174            let w = CVPixelBufferGetWidth(pixelBuffer), h = CVPixelBufferGetHeight(pixelBuffer), row = CVPixelBufferGetBytesPerRow(pixelBuffer)175            let step = max(1, max(w, h) / 900)176            let sw = w / step, sh = h / step177            guard sw >= 3, sh >= 3 else { return nil }178            let px = base.assumingMemoryBound(to: UInt8.self)179            var luma = [UInt8](repeating: 0, count: sw * sh)180            for y in 0..<sh {181                let line = px + y * step * row182                for x in 0..<sw {183                    let p = line + x * step * 4184                    luma[y * sw + x] = UInt8((UInt32(p[2]) * 77 + UInt32(p[1]) * 150 + UInt32(p[0]) * 29) >> 8)185                }186            }187            return LumaQuality.measure(luma: luma, width: sw, height: sh)188        }189        return nil190    }191}192
Files main
Menu

Theme