加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:47:13 所属栏目:百科 来源:网络整理
导读:我正在制作照片编辑应用程序. 当用户选择照片时,使用以下代码将其自动转换为黑白照片: func blackWhiteImage(image: UIImage) - Data { print("Starting black white") let orgImg = CIImage(image: image) let bnwImg = orgImg?.applyingFilter("CIColorCo
我正在制作照片编辑应用程序.

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

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读