[swift] AlamofireImage를 사용하여 이미지에서 색상 추출하기

이미지에서 색상을 추출하는 것은 다양한 애플리케이션에서 유용한 작업입니다. Swift에서는 AlamofireImage라이브러리를 사용하여 이미지에서 색상을 추출할 수 있습니다.

1. AlamofireImage 라이브러리 설치하기

먼저, AlamofireImage를 프로젝트에 추가해야 합니다. 이를 위해 Podfile에 다음과 같이 추가합니다.

pod 'AlamofireImage'

그리고 터미널에서 다음 명령어를 실행하여 라이브러리를 설치합니다.

$ pod install

2. 이미지에서 색상 추출하기

다음은 AlamofireImage를 사용하여 이미지에서 색상을 추출하는 예제 코드입니다.

import AlamofireImage

func extractColors(from image: UIImage, completion: @escaping ([UIColor]) -> Void) {
    if let cgImage = image.cgImage {
        let imageURL = ImageURLProvider(url: "dummy") // 임시 URL 설정
        let imageFilter = AspectScaledToFillSizeFilter(size: CGSize(width: 100, height: 100))
        
        let imageRequest = ImageRequest(urlRequest: URLRequest(url: imageURL.url), targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill)
        
        AFImageDownloader.default.download(imageRequest, filter: imageFilter, progress: nil) { response in
            guard let image = response.result.value,
                  let resizedCGImage = image.cgImage else {
                completion([])
                return
            }
            
            let colors = resizedCGImage.getPixelColors()
            completion(colors)
        }
    } else {
        completion([])
    }
}

위의 코드에서 extractColors 함수는 패러미터로 받은 이미지에서 색상을 추출하고 추출된 색상들을 completion 클로저를 통해 반환합니다.

추출된 색상들은 CGImagegetPixelColors 확장 메소드를 사용하여 추출되며, 이 확장 메소드는 다음과 같이 구현할 수 있습니다.

import UIKit

extension CGImage {
    func getPixelColors() -> [UIColor] {
        var colors: [UIColor] = []
        
        let width = self.width
        let height = self.height
        
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bitsPerComponent = 8
        
        let imageData = malloc(bytesPerRow * height)
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let context = CGContext(data: imageData,
                                width: width,
                                height: height,
                                bitsPerComponent: bitsPerComponent,
                                bytesPerRow: bytesPerRow,
                                space: colorSpace,
                                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)
        
        context?.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height))
        
        if let data = context?.data {
            let buffer = data.bindMemory(to: UInt8.self, capacity: width * height * bytesPerPixel)
            
            for y in 0..<height {
                for x in 0..<width {
                    let byteIndex = bytesPerRow * y + bytesPerPixel * x
                    let red = CGFloat(buffer[byteIndex]) / 255.0
                    let green = CGFloat(buffer[byteIndex + 1]) / 255.0
                    let blue = CGFloat(buffer[byteIndex + 2]) / 255.0
                    let alpha = CGFloat(buffer[byteIndex + 3]) / 255.0
                    
                    let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
                    colors.append(color)
                }
            }
        }
        
        free(imageData)
        
        return colors
    }
}

3. 사용 예시

이제 extractColors 함수를 사용하여 이미지에서 색상을 추출하는 방법을 알아보겠습니다.

let image = UIImage(named: "example_image")
extractColors(from: image) { colors in
    // 추출된 색상들 사용
    for color in colors {
        print(color)
    }
}

위의 코드에서는 extractColors 함수를 호출하고, 추출된 색상들을 colors 배열로 받아와서 사용하는 예시입니다.


참고 자료: