When adding similar-photo alerts to an iOS project maintained on Windows, comparing file hashes is not enough: recompressing the same image changes its bytes. Start by running a standalone Swift test harness on a LoopMac cloud Mac to establish consistent image conversion rules and distance calculations before integrating them into the app. This article implements dHash for candidate screening, not as a basis for automatic deletion.
Define the input contract for similarity detection
dHash reduces an image to nine columns by eight rows, then compares eight pairs of adjacent pixels in each row to produce a 64-bit fingerprint. The number of set bits in the XOR of two fingerprints is their Hamming distance, ranging from zero to 64. A smaller distance means only that the brightness structures appear more similar under these thumbnail-generation rules.
Limit the input to static images: apply orientation metadata, composite transparent areas onto white, convert to a common grayscale representation, and then resize. Reject animated images and multipage containers outright rather than silently taking the first frame. Set an input pixel limit as well. This example uses a limit of 40 million pixels—a resource policy for the test program, not a service configuration setting.
A perceptual fingerprint answers “Are these worth showing together for the user to review?” A file hash answers “Are the bytes identical?” Neither can replace the other, and a distance of zero is never sufficient grounds for deleting an original.
Generate reproducible fingerprints on a cloud Mac
First, run xcrun --find swift to confirm that the toolchain is available. Save the following as dhash.swift and run it in a directory containing two test images. The code uses system imaging frameworks and requires no third-party packages. The production app should reuse this implementation rather than introduce a separate approximation.
import Foundation
import CoreGraphics
import ImageIO
enum HashError: Error {
case invalidInput
case renderingFailed
}
func fingerprint(_ path: String) throws -> UInt64 {
let url = URL(fileURLWithPath: path)
guard
let source = CGImageSourceCreateWithURL(url as CFURL, nil),
CGImageSourceGetCount(source) == 1,
let info = CGImageSourceCopyPropertiesAtIndex(
source, 0, nil
) as? [CFString: Any],
let width = (info[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue,
let height = (info[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue,
width > 0, height > 0,
width <= 40_000_000 / height
else {
throw HashError.invalidInput
}
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: 64,
kCGImageSourceShouldCacheImmediately: true
]
guard let image = CGImageSourceCreateThumbnailAtIndex(
source, 0, options as CFDictionary
) else {
throw HashError.invalidInput
}
var pixels = [UInt8](repeating: 0, count: 72)
try pixels.withUnsafeMutableBytes { bytes in
guard let context = CGContext(
data: bytes.baseAddress,
width: 9,
height: 8,
bitsPerComponent: 8,
bytesPerRow: 9,
space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: CGImageAlphaInfo.none.rawValue
) else {
throw HashError.renderingFailed
}
let rect = CGRect(x: 0, y: 0, width: 9, height: 8)
context.setFillColor(gray: 1, alpha: 1)
context.fill(rect)
context.interpolationQuality = .medium
context.draw(image, in: rect)
}
var result: UInt64 = 0
for row in 0..<8 {
for column in 0..<8 {
result <<= 1
let offset = row * 9 + column
if pixels[offset] > pixels[offset + 1] {
result |= 1
}
}
}
return result
}
guard CommandLine.arguments.count == 3 else {
fatalError("Expected two image paths")
}
let first = try fingerprint(CommandLine.arguments[1])
let second = try fingerprint(CommandLine.arguments[2])
let distance = (first ^ second).nonzeroBitCount
let report = "\(String(first, radix: 16)) \(String(second, radix: 16)) \(distance)\n"
FileHandle.standardOutput.write(Data(report.utf8))
Run xcrun swift dhash.swift original.jpg recompressed.jpg. The output contains the two hexadecimal fingerprints followed by their distance. Preserve the error exit status if the script fails. Do not map read failures to an all-zero fingerprint, or corrupted files will end up in the same group.
Calibrate the threshold with paired fixtures
Prepare clearly labeled samples in three categories: compressed and resized versions of the same source image, photos of the same scene with different content, and completely unrelated images. For each pair, record the file hashes, source relationship, expected label, and measured distance. Keep the fixtures under version control and leave the originals unchanged. Obtain permission before using material featuring people.
Do not set the threshold from a single photo
Calculate distances for all samples first, then try candidate thresholds one by one and count false positives and false negatives. Raising the threshold generally produces more candidates, but also more incorrect matches for users to dismiss. A small distance for one recompressed image does not establish a rule for all photos. Examine screenshots, scans, and everyday photos separately.
At a minimum, the test report should distinguish between pairs that should have been selected as candidates but were missed, and pairs that should not have been selected but were included. Candidate alerts can tolerate some false positives. Automatic merging requires stronger evidence and is outside the scope of this example.
Deliberately include failure-prone edge cases
Start with black, white, and other solid-color images. When adjacent pixels have equal brightness, the fingerprint may be all zeros, so different colors can produce collisions. Then add images whose colors change while their brightness structure stays the same, and verify that the product does not describe a grayscale fingerprint as a color-consistency check.
For orientation fixtures, save equivalent versions with the pixels physically rotated and with only the orientation tag changed, then check the normalized results. For transparent images, include both the transparent original and a version already composited onto white. This tests the white-background contract; the result does not extend to arbitrary display backgrounds.
Cropping, mirroring, and adding a large watermark may change the fingerprint, or may leave it close by chance. Treat these cases as limits of the algorithm rather than continually loosening the threshold to make every variant pass. Corrupted files, multiframe inputs, and oversized images must take the rejection path, not enter the candidate list.
Integrate the fixtures into regression testing
On the cloud Mac, record the OS version, Swift version, source revision, and fixture hashes. Run the script for each pair and report every read error separately. Repeated runs with the same input should produce the same fingerprint. Swapping the two images should leave the distance unchanged, and comparing an image with itself must yield zero.
System decoding, grayscale conversion, and interpolation implementations may change between versions, so do not claim that fingerprints will always remain identical across versions. Store an algorithm version with persisted records. After updating the conversion pipeline, run the existing fixtures before deciding whether to rebuild the index. Do not mix distances from two algorithm versions.
Finally, have the interface show only candidates and previews of the originals, with confirmation still required for deletion. Acceptance is not about having “found a few similar images.” It means that normal samples have measured results, edge cases are handled, false positives can be explained, and no decision damages the original files.
Frequently asked questions
Does an identical dHash prove that two images are identical?
No. dHash retains only coarse brightness relationships. Solid colors and unrelated images can collide. Use a separate file digest for byte equality and review visual candidates.
Which Hamming-distance threshold should I use?
Calibrate it against labeled pairs from your own image collection. Compare true variants with unrelated images, then choose a threshold based on the cost of false positives and missed matches.
Choose a cloud Mac for your next project
Need a macOS GUI or command line? Start by choosing a model, location, and billing period that fit your project. After payment, provisioning begins. Check the console for real-time availability.
Choose a cloud Mac plan