colla2me/Notes

CIFilterImage Code Snippet

colla2me opened this issue · 0 comments

code snippet

  • Filter
import CoreImage

public struct Filter {
    let name: String
    let ciFilterName: String?

    public init(name: String, ciFilterName: String?) {
        self.name = name
        self.ciFilterName = ciFilterName
    }
}

extension Filter: Equatable {
    public static func ==(lhs: Filter, rhs: Filter) -> Bool {
        return lhs.name == rhs.name
    }
}

extension Filter {
    static var all: [Filter] = [
        Filter(name: "Normal", ciFilterName: nil),
        Filter(name: "Chrome", ciFilterName: "CIPhotoEffectChrome"),
        Filter(name: "Fade", ciFilterName: "CIPhotoEffectFade"),
        Filter(name: "Instant", ciFilterName: "CIPhotoEffectInstant"),
        Filter(name: "Mono", ciFilterName: "CIPhotoEffectMono"),
        Filter(name: "Noir", ciFilterName: "CIPhotoEffectNoir"),
        Filter(name: "Process", ciFilterName: "CIPhotoEffectProcess"),
        Filter(name: "Tonal", ciFilterName: "CIPhotoEffectTonal"),
        Filter(name: "Transfer", ciFilterName: "CIPhotoEffectTransfer"),
        Filter(name: "Tone", ciFilterName: "CILinearToSRGBToneCurve"),
        Filter(name: "Linear", ciFilterName: "CISRGBToneCurveToLinear"),
        Filter(name: "Sepia", ciFilterName: "CISepiaTone"),
    ]
}
  • FilterProvider
import CoreImage

final class FilterProvider {

    static let shared: FilterProvider = .init()

    private init () {}

    private let context = CIContext(options: nil)

    func applyFilter(with image: UIImage, filter: Filter) -> UIImage {
        guard let ciFilterName = filter.ciFilterName else {
            return image
        }

        let sourceImage = CIImage(image: image)
        let filter = CIFilter(name: ciFilterName)
        filter?.setDefaults()
        filter?.setValue(sourceImage, forKey: kCIInputImageKey)
        let outputCGImage = context.createCGImage((filter?.outputImage!)!, from: (filter?.outputImage!.extent)!)
        let filteredImage = UIImage(cgImage: outputCGImage!)

        return filteredImage
    }
}

extension UIImage {
    static func resize(with image: UIImage, ratio: CGFloat = 0.2) -> UIImage {
        let resizedSize = CGSize(width: Int(image.size.width * ratio), height: Int(image.size.height * ratio))
        UIGraphicsBeginImageContext(resizedSize)
        image.draw(in: CGRect(x: 0, y: 0, width: resizedSize.width, height: resizedSize.height))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resizedImage!
    }
}