Created
July 23, 2019 08:46
-
-
Save Que20/0c0a36729ed32316954a8068b2f29402 to your computer and use it in GitHub Desktop.
Check if an image is dark in Swift.
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
func imageIsDark(image: CGImage) -> Bool { | |
let redLum = 0.299 | |
let greenLum = 0.578 | |
let blueLum = 0.114 | |
let maxLum = 150.0 | |
guard let imageData = image.dataProvider?.data else { return false } | |
guard let ptr = CFDataGetBytePtr(imageData) else { return false } | |
let length = CFDataGetLength(imageData) | |
let threshold = Int(Double(image.width * image.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 = (redLum * Double(r) + greenLum * Double(g) + blueLum * Double(b)) | |
if luminance < maxLum { | |
darkPixels += 1 | |
if darkPixels > threshold { | |
return true | |
} | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment