Skip to content

Instantly share code, notes, and snippets.

@Que20
Created July 23, 2019 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Que20/0c0a36729ed32316954a8068b2f29402 to your computer and use it in GitHub Desktop.
Save Que20/0c0a36729ed32316954a8068b2f29402 to your computer and use it in GitHub Desktop.
Check if an image is dark in Swift.
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