import CoreGraphics import Foundation import ImageIO /// 画像を1回デコードして得られる基本情報。dHash と表示用メタデータをまとめて取る。 struct ImageBasics: Codable, Hashable, Sendable { let dHash: UInt64 let pixelWidth: Int let pixelHeight: Int let captureDate: Date? } /// 隣接ピクセルの明暗差から 64bit の知覚ハッシュ(dHash)を作る。 /// /// リサイズや再圧縮では値がほとんど変わらないので、feature print にかける候補ペアを /// 安く絞り込むための一次フィルタとして使う。 enum DHash { /// 9×8 に落として横隣接を比較するので 8×8 = 64bit になる。 private static let hashWidth = 9 private static let hashHeight = 8 static func compute(for url: URL) -> ImageBasics? { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), CGImageSourceGetCount(source) > 0 else { return nil } let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] let (width, height) = pixelSize(from: properties) let captureDate = captureDate(from: properties) // フルデコードを避けるため、まず小さなサムネイルを取り出す。 // WithTransform で EXIF の回転を適用しておく。Vision の feature print も同じく EXIF を // 反映するので、これで「表示したときの見た目」どうしを比較する形に揃う。 // 結果として、回転が焼き込まれた版と EXIF で回している版は同じ写真として検出できる一方、 // 実際に向きが違う写真どうしは別物として扱われる。 let thumbnailOptions: [CFString: Any] = [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceThumbnailMaxPixelSize: 64, ] guard let thumbnail = CGImageSourceCreateThumbnailAtIndex( source, 0, thumbnailOptions as CFDictionary ) else { return nil } guard let hash = hash(of: thumbnail) else { return nil } return ImageBasics( dHash: hash, pixelWidth: width, pixelHeight: height, captureDate: captureDate ) } /// 2つのハッシュがどれだけ違うか(異なるビット数)。 static func hammingDistance(_ a: UInt64, _ b: UInt64) -> Int { (a ^ b).nonzeroBitCount } // MARK: - 内部 private static func hash(of image: CGImage) -> UInt64? { let bytesPerRow = 16 // hashWidth(9) 以上で 16 バイト境界に揃える var buffer = [UInt8](repeating: 0, count: bytesPerRow * hashHeight) let ok = buffer.withUnsafeMutableBytes { raw -> Bool in guard let context = CGContext( data: raw.baseAddress, width: hashWidth, height: hashHeight, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue ) else { return false } context.interpolationQuality = .medium context.draw( image, in: CGRect(x: 0, y: 0, width: hashWidth, height: hashHeight) ) return true } guard ok else { return nil } var hash: UInt64 = 0 var bit = 0 for y in 0.. buffer[row + x + 1] { hash |= (1 << UInt64(bit)) } bit += 1 } } return hash } private static func pixelSize(from properties: [CFString: Any]?) -> (Int, Int) { let width = properties?[kCGImagePropertyPixelWidth] as? Int ?? 0 let height = properties?[kCGImagePropertyPixelHeight] as? Int ?? 0 // EXIF の回転を反映した「見た目の」サイズを返す。 let orientation = properties?[kCGImagePropertyOrientation] as? Int ?? 1 return (5...8).contains(orientation) ? (height, width) : (width, height) } private static func captureDate(from properties: [CFString: Any]?) -> Date? { guard let exif = properties?[kCGImagePropertyExifDictionary] as? [CFString: Any] else { return nil } let raw = exif[kCGImagePropertyExifDateTimeOriginal] as? String ?? exif[kCGImagePropertyExifDateTimeDigitized] as? String guard let raw else { return nil } return exifDateFormatter.date(from: raw) } /// EXIF の日時は "2024:05:01 12:34:56" 形式。 private static let exifDateFormatter: DateFormatter = { let f = DateFormatter() f.locale = Locale(identifier: "en_US_POSIX") f.dateFormat = "yyyy:MM:dd HH:mm:ss" return f }() }