How to calculate the average color of a UIImage?

前端 未结 6 1731
花落未央
花落未央 2021-02-01 07:55

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

6条回答
  •  礼貌的吻别
    2021-02-01 08:24

    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)
    }
    

    }

提交回复
热议问题