Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Created June 24, 2020 10:17
Show Gist options
  • Select an option

  • Save lamprosg/63dce48ab545a698bee3dbb3ab09468a to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/63dce48ab545a698bee3dbb3ab09468a to your computer and use it in GitHub Desktop.

Revisions

  1. lamprosg created this gist Jun 24, 2020.
    46 changes: 46 additions & 0 deletions UIImage+Darkness.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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
    }
    }