我正在制作照片编辑应用程序.
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中使用?
只需开始一个新的图形上下文并在那里绘制灰度图像:
原文链接:/swift/320126.htmlfunc 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 }