[swift] CoreGraphics 이미지 처리

이미지 처리는 모바일 애플리케이션에서 매우 중요한 부분이며, CoreGraphics 프레임워크를 사용하여 iOS에서 이미지를 처리하기 위한 강력한 기능을 제공합니다.

이미지 리사이징

CoreGraphics를 사용하여 이미지를 리사이즈하려면 UIGraphicsBeginImageContextWithOptions 메서드를 사용하여 새로운 이미지 그래픽 컨텍스트를 만들어야 합니다. 그런 다음 draw(in:) 메서드를 사용하여 원하는 크기로 이미지를 그려야 합니다. 최종적으로 UIGraphicsGetImageFromCurrentImageContext 메서드를 호출하여 새로 생성된 이미지를 얻을 수 있습니다.

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? {
  let scale = newWidth / image.size.width
  let newHeight = image.size.height * scale
  let newSize = CGSize(width: newWidth, height: newHeight)

  UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
  image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
  let newImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()

  return newImage
}

이미지 회전

CoreGraphics를 사용하여 이미지를 회전하려면 UIGraphicsBeginImageContextWithOptions를 사용하여 이미지를 그리기 전에 새로운 이미지 그래픽 컨텍스트를 만들어야 합니다. 그런 다음 CGContextRotateCTM 메서드를 사용하여 이미지를 회전시켜야 합니다.

func rotateImage(image: UIImage, angle: Int) -> UIImage? {
  let radians = CGFloat(angle) * CGFloat.pi / 180
  let newRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)

  UIGraphicsBeginImageContextWithOptions(image.size, false, 0.0)
  if let context = UIGraphicsGetCurrentContext() {
    context.translateBy(x: image.size.width / 2, y: image.size.height / 2)
    context.rotate(by: radians)
    image.draw(in: newRect)
  }
  let newImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()

  return newImage
}

이미지 필터링

CoreGraphics를 사용하여 이미지에 필터를 적용하려면 Core Image 프레임워크를 사용하여 이미지를 필터링해야 합니다.

import CoreImage

func applyFilter(to image: UIImage) -> UIImage? {
    let ciContext = CIContext(options: nil)
    if let coreImage = CIImage(image: image) {
        let filter = CIFilter(name: "CIPhotoEffectMono")
        filter?.setDefaults()
        filter?.setValue(coreImage, forKey: kCIInputImageKey)

        if let output = filter?.outputImage,
           let cgImage = ciContext.createCGImage(output, from: output.extent) {
            return UIImage(cgImage: cgImage)
        }
    }
    return nil
}

위 코드에서 CIPhotoEffectMono는 이미지에 흑백 필터를 적용합니다.

CoreGraphics를 사용하여 이미지를 처리하는 기술은 iOS 개발에서 매우 중요한 요소이며, 이미지 리사이징, 회전, 필터링과 같은 작업을 수행하는데 많은 도움이 됩니다.

이상으로 CoreGraphics를 사용하여 이미지 처리하는 간단한 방법에 대한 소개였습니다. CoreGraphics의 다양한 기능을 활용하여 더 복잡하고 강력한 이미지 처리 알고리즘을 구현할 수 있습니다.

Apple Documentation - CoreGraphics Apple Documentation - Core Image