I want to build an app that lets the user select an image and it outputs the \"average color\".
For example, this image:
The average color would be a gr
I end up with this class extension:
extension UIImage {
func averageColor(alpha : CGFloat) -> UIColor {
let rawImageRef : CGImageRef = self.CGImage!
let data : CFDataRef = CGDataProviderCopyData(CGImageGetDataProvider(rawImageRef))!
let rawPixelData = CFDataGetBytePtr(data);
let imageHeight = CGImageGetHeight(rawImageRef)
let imageWidth = CGImageGetWidth(rawImageRef)
let bytesPerRow = CGImageGetBytesPerRow(rawImageRef)
let stride = CGImageGetBitsPerPixel(rawImageRef) / 6
var red = 0
var green = 0
var blue = 0
for row in 0...imageHeight {
var rowPtr = rawPixelData + bytesPerRow * row
for _ in 0...imageWidth {
red += Int(rowPtr[0])
green += Int(rowPtr[1])
blue += Int(rowPtr[2])
rowPtr += Int(stride)
}
}
let f : CGFloat = 1.0 / (255.0 * CGFloat(imageWidth) * CGFloat(imageHeight))
return UIColor(red: f * CGFloat(red), green: f * CGFloat(green), blue: f * CGFloat(blue) , alpha: alpha)
}
}