swift – 来自CIImage的PNG / JPEG表示总是返回nil

前端之家收集整理的这篇文章主要介绍了swift – 来自CIImage的PNG / JPEG表示总是返回nil前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在制作照片编辑应用程序.

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

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中使用?

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

只需开始一个新的图形上下文并在那里绘制灰度图像:
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,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
}
原文链接:/swift/320126.html

猜你在找的Swift相关文章