Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Created June 24, 2020 10:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamprosg/63dce48ab545a698bee3dbb3ab09468a to your computer and use it in GitHub Desktop.
Save lamprosg/63dce48ab545a698bee3dbb3ab09468a to your computer and use it in GitHub Desktop.
(iOS) Check image darkness
import UIKit
// Call CGImage mechanism from a UIImage
@objc extension UIImage {
var isDark: Bool {
self.cgImage?.isDark ?? false
}
}
// Detect if a CGImage's luminance is Dark of Bright
/*
Works by getting the pointer of the bitmap image Data,
Iterate every 4 Bytes, get the r g b values by advancing the pointer,
detect if the rgb luminance is dark or bright.
If the count of dark Bytes is greater than the threshold we indicate the image is Dark
*/
extension CGImage {
private var thresholdModifier: Double {
0.45
}
var isDark: Bool {
guard let imageData = self.dataProvider?.data else { return false }
guard let ptr = CFDataGetBytePtr(imageData) else { return false }
let dataLength = CFDataGetLength(imageData)
let threshold = Int(Double(self.width * self.height) * thresholdModifier)
var darkPixelsCount = 0
for i in stride(from: 0, to: dataLength, 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 {
darkPixelsCount += 1
if darkPixelsCount > threshold { return true }
}
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment