Created
June 24, 2020 10:17
-
-
Save lamprosg/63dce48ab545a698bee3dbb3ab09468a to your computer and use it in GitHub Desktop.
(iOS) Check image darkness
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
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