Skip to content

Commit

Permalink
Fix averageColor
Browse files Browse the repository at this point in the history
  • Loading branch information
aromanov91 committed Nov 10, 2024
1 parent 5fc903c commit c87ac67
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Sources/OversizeCore/Extensions/Image/NSImage+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,23 @@
cgImage(forProposedRect: nil, context: nil, hints: nil)
}
}

public extension NSImage {
var averageColor: NSColor? {
guard let cgImage = cgImage(forProposedRect: nil, context: nil, hints: nil) else { return nil }
let inputImage = CIImage(cgImage: cgImage)

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 NSColor(red: CGFloat(bitmap[0]) / 255, green: CGFloat(bitmap[1]) / 255, blue: CGFloat(bitmap[2]) / 255, alpha: CGFloat(bitmap[3]) / 255)
}
}

#endif
26 changes: 26 additions & 0 deletions Sources/OversizeCore/Extensions/Image/UIImage+Extension.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//
// Copyright © 2024 Alexander Romanov
// File.swift, created on 07.11.2024
//

#if canImport(UIKit)
import UIKit
#endif

#if canImport(UIKit)
public extension UIImage {
var averageColor: UIColor? {
guard let inputImage = CIImage(image: self) else { return nil }
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)
}
}
#endif

0 comments on commit c87ac67

Please sign in to comment.