当用户选择照片时,使用以下代码将其自动转换为黑白照片:
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 – 来自CIImage的PNG / JPEG表示总是返回nil全部内容,希望文章能够帮你解决swift – 来自CIImage的PNG / JPEG表示总是返回nil所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)