Created
May 30, 2023 13:35
-
-
Save joaomvfsantos/5af87b08939f3be249c8f26cc7c454d2 to your computer and use it in GitHub Desktop.
Swift UIImage Extension that generates a grayscale copy of the original image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIImageToGrayscale.swift | |
// | |
// Created by João Santos on 27/11/2018. | |
// Copyright © 2018 João Santos. All rights reserved. | |
// | |
import UIKit | |
extension UIImage { | |
func grayscaleImage() -> UIImage? { | |
guard let cgImage = self.cgImage, let filter = CIFilter(name: "CIPhotoEffectTonal") else { return nil } | |
filter.setDefaults() | |
filter.setValue(CIImage(cgImage: cgImage), forKey: kCIInputImageKey) | |
guard let outputImage = filter.outputImage, let imageRef = CIContext(options: nil).createCGImage(outputImage, from: outputImage.extent) else { return nil } | |
return UIImage(cgImage: imageRef) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment