Last active
November 16, 2024 19:18
-
-
Save juliensagot/602f27776fdf0e0d7c92dd52a2f94662 to your computer and use it in GitHub Desktop.
Get the average color of a UIImage. (Swift 4.2, Xcode 10.0)
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 | |
extension UIImage { | |
var averageColor: UIColor? { | |
guard let inputImage = self.ciImage ?? CIImage(image: self) else { return nil } | |
guard let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: CIVector(extent: inputImage.extent)]) | |
else { return nil } | |
guard let outputImage = filter.outputImage else { return nil } | |
var bitmap = [UInt8](repeating: 0, count: 4) | |
let context = CIContext(options: [CIContextOption.workingColorSpace : kCFNull]) | |
let outputImageRect = CGRect(x: 0, y: 0, width: 1, height: 1) | |
context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: outputImageRect, format: CIFormat.RGBA8, colorSpace: nil) | |
return UIColor(red: CGFloat(bitmap[0]) / 255, green: CGFloat(bitmap[1]) / 255, blue: CGFloat(bitmap[2]) / 255, alpha: CGFloat(bitmap[3) / 255) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment