-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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