[swift] Swift Core Graphics로 이미지 흑백 변환하기

Core Graphics 라이브러리를 사용하여 Swift로 쉽게 이미지를 흑백으로 변환할 수 있습니다. 이 기술 블로그에서는 이러한 변환을 수행하는 방법에 대해 알아보겠습니다.

Core Graphics 소개

Core Graphics는 iOS 및 macOS 애플리케이션에서 그래픽을 그리고 이미지를 조작하는 데 사용되는 프레임워크입니다. 이를 사용하여 이미지를 흑백으로 변환할 수 있습니다.

이미지 흑백으로 변환하기

다음은 Core Graphics를 사용하여 이미지를 흑백으로 변환하는 예제 코드입니다.

import UIKit

func convertToGrayscale(image: UIImage) -> UIImage? {
    guard let cgImage = image.cgImage else {
        return nil
    }

    let colorSpace = CGColorSpaceCreateDeviceGray()

    let width = cgImage.width
    let height = cgImage.height

    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)

    guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else {
        return nil
    }

    context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))

    guard let outputCGImage = context.makeImage() else {
        return nil
    }

    let outputImage = UIImage(cgImage: outputCGImage)

    return outputImage
}

위의 코드는 convertToGrayscale 함수를 사용하여 입력으로 받은 이미지를 흑백으로 변환합니다. 이 함수는 UIImage 객체를 받아들이고, 해당 이미지를 흑백으로 변환한 후 UIImage로 반환합니다.

마무리

이제 Swift로 Core Graphics를 사용하여 이미지를 흑백으로 변환하는 방법을 배웠습니다. 이 기술을 사용하여 이미지 처리 관련 다양한 작업을 수행할 수 있습니다.

더 많은 정보를 원하시면 Core Graphics Documentation를 참고하십시오.