来自CIImage的PNG / JPEG表示始终返回nil

时间:2017-03-03 23:44:47

标签: swift uiimage ciimage uiimagejpegrepresentation uiimagepngrepresentation

我目前正在制作照片编辑应用。

当用户选择照片时,使用以下代码自动将其转换为黑白照片:

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)!
}

我对此代码遇到的问题是我一直收到此错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

我的代码配置略有不同,但是当它到达UIImagePNG/JPEGRepresentation(xx)部分时仍然会中断。

有没有办法从CIImage中获取PNG或JPEG数据,以便在图像视图/ UIImage中使用?

任何其他方法都没有详细说明应该使用哪些代码。

1 个答案:

答案 0 :(得分:6)

只需开始新的图形上下文并在那里绘制灰度图像:

func blackWhiteImage(image: UIImage) -> Data? {
    guard let ciImage = CIImage(image: image)?.applyingFilter("CIColorControls", parameters: [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 redraw.pngData()  // Swift 4.2 Xcode 10 or later
    // return UIImagePNGRepresentation(redraw) Swift 4.1 - Xcode lower than 10
}

您还可以扩展UIImage以返回灰度图像:

extension UIImage {
    var grayscale: UIImage? {
        guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", parameters: [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 = grayscale.pngData() {  // or Swift 4.1 or earlier -> let data = UIImagePNGRepresentation(grayscale)
    print(data.count)   //  689035
}