Skip to content

Instantly share code, notes, and snippets.

@unuigbee
Forked from adamcichy/ImageDarkness.swift
Created September 14, 2021 17:11
Show Gist options
  • Save unuigbee/868f88d28bbb71926d501197ad454131 to your computer and use it in GitHub Desktop.
Save unuigbee/868f88d28bbb71926d501197ad454131 to your computer and use it in GitHub Desktop.
Determine if a UIImage is generally dark or generally light in Swift 3
extension CGImage {
var isDark: Bool {
get {
guard let imageData = self.dataProvider?.data else { return false }
guard let ptr = CFDataGetBytePtr(imageData) else { return false }
let length = CFDataGetLength(imageData)
let threshold = Int(Double(self.width * self.height) * 0.45)
var darkPixels = 0
for i in stride(from: 0, to: length, by: 4) {
let r = ptr[i]
let g = ptr[i + 1]
let b = ptr[i + 2]
let luminance = (0.299 * Double(r) + 0.587 * Double(g) + 0.114 * Double(b))
if luminance < 150 {
darkPixels += 1
if darkPixels > threshold {
return true
}
}
}
return false
}
}
}
extension UIImage {
var isDark: Bool {
get {
return self.cgImage?.isDark ?? false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment