The PNG / JPEG view from CIImage always returns nil

I am currently making a photo editing application.

When a user selects a photo, it is automatically converted to a black and white code using this code:

func blackWhiteImage(image: UIImage) -> Data {
    print("Starting black & white")

    let orgImg = CIImage(image: image)
    let bnwImg = orgImg?.applyingFilter("CIColorControls", withInputParameters: [kCIInputSaturationKey:0.0])

    let outputImage = UIImage(ciImage: bnwImg!)

    print("Black & white complete")

    return UIImagePNGRepresentation(outputImage)!
}

The problem with this code is that I keep getting this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I had my code in a slightly different configuration, but it still breaks when it gets into the section UIImagePNG/JPEGRepresentation(xx).

Is there a way to get PNG or JPEG data from CIImage for use in image presentation or just UIImage in general?

Any of the other methods do not contain sufficiently detailed information about which code should be used.

+4
1

:

func blackWhiteImage(image: UIImage) -> Data? {
    guard let ciImage = CIImage(image: image)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputSaturationKey:0.0]) else { return nil }
    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    defer { UIGraphicsEndImageContext() }
    UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: image.size))
    guard let redraw = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
    return UIImagePNGRepresentation(redraw)
}

UIImage, :

extension UIImage {
    var grayscale: UIImage? {
        guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputSaturationKey: 0]) else { return nil }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer { UIGraphicsEndImageContext() }
        UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!

if let grayscale = profilePicture.grayscale, let data = UIImagePNGRepresentation(grayscale) {
    print(data.count)   //  689035
}
+3

Source: https://habr.com/ru/post/1671413/


All Articles