Swift Recipe

Get Average Colour From UIImage

To get the average colour from any UIImage we will be using Core Image CIFilter class.

Here is an extension of UIImage that will give the average color of the entire image and it returns nil if there is something wrong with your image:

extension UIImage {
    var getAverageColour: UIColor? {
        //A CIImage object is the image data you want to process.
        guard let inputImage = CIImage(image: self) else { return nil }
        // A CIVector object representing the rectangular region of inputImage .
        let extentVector = CIVector(x: inputImage.extent.origin.x, y: inputImage.extent.origin.y, z: inputImage.extent.size.width, w: inputImage.extent.size.height)
        guard let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: extentVector]) else { return nil }
        guard let outputImage = filter.outputImage else { return nil }

        var bitmap = [UInt8](repeating: 0, count: 4)
        let context = CIContext(options: [.workingColorSpace: kCFNull])
        context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: .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)

Use above extension to get the average colour from any UIImage.

Sample Output:

get average colour from uiimage
Average color from the image

This is a very useful feature when you want to have a background according to the image on the view.

Instagram uses this on their stories feature. You must have noticed it when you share a post or any image on your story, it picks up the average color of the image and fills the whole background of the story with that average color.

You can subclass CIFilter to create your own custom filter effects. Apple provides a good reference document on Core Image Filters.

Learn how to add animations to your SwiftUi app here!

Checkout another quick article on How To Add Splash Screen in SwiftUI.

If you want to learn how to use SwiftUI in your existing app, then you can read it here!

or If you want to learn how to use and convert your UIViewControllers in SwiftUI, then you can read it here!

Like it? Share with your friends!


Your email address will not be published. Required fields are marked *