extract average colour from image in swift

Here is the Swift code to extract the average color from an UIImage in iOS using Core Graphics:

main.swift
func getAverageColor(from image: UIImage) -> UIColor? {
    // Convert to CGImage to access the pixel data
    guard let cgImage = image.cgImage else { return nil }
    
    // Define values to track the total RGB values and the count of pixels 
    var totalR = 0
    var totalG = 0
    var totalB = 0
    var count = 0
    
    // Define the size of the image and the RGB color space to use 
    let width = cgImage.width
    let height = cgImage.height
    let bytesPerRow = width * 4
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
    
    // Create a context to work with the pixel data
    let context = CGContext(data: nil,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bytesPerRow,
                            space: colorSpace,
                            bitmapInfo: bitmapInfo)!
    // Draw the image into the context to access the pixel data
    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    context.draw(cgImage, in: rect)
    
    // Loop through the pixel data to calculate the average RGB values
    let data = context.data!.assumingMemoryBound(to: UInt8.self)
    for x in 0..<width {
        for y in 0..<height {
            let offset = 4 * (y * width + x)
            let r = Int(data[offset])
            let g = Int(data[offset + 1])
            let b = Int(data[offset + 2])
            totalR += r
            totalG += g
            totalB += b
            count += 1
        }
    }
    
    // Calculate the average RGB values and return the resulting UIColor object
    let avgR = totalR / count
    let avgG = totalG / count
    let avgB = totalB / count
    return UIColor(red: CGFloat(avgR) / 255, green: CGFloat(avgG) / 255, blue: CGFloat(avgB) / 255, alpha: 1)
}
1953 chars
51 lines

This code creates a CGContext using the image's pixel data and loops through each pixel, calculating the average RGB values. It then returns a UIColor object with the calculated average color.

gistlibby LogSnag