我目前正在制作照片编辑应用。
用户选择了照片后,将使用以下代码将其自动转换为黑白:
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)节时仍然会中断。
UIImagePNG/JPEGRepresentation(xx)
是否有任何方法可以从CIImage获取PNG或JPEG数据以用于图像视图(通常仅是UIImage)?
其他任何方法都没有详细说明应使用什么代码。
只需开始一个新的图形上下文并在那里绘制您的灰度图像即可。iOS 10或更高版本,您可以使用UIGraphicsImageRenderer,对于较旧的iOS版本语法,请检查编辑历史记录:
Xcode 11•Swift 5.1
func blackWhiteImage(image: UIImage, isOpaque: Bool = false) -> Data? { guard let ciImage = CIImage(image: image)?.applyingFilter("CIColorControls", parameters: [kCIInputSaturationKey: 0]) else { return nil } let format = image.imageRendererFormat format.opaque = isOpaque return UIGraphicsImageRenderer(size: image.size, format: format).image { _ in UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: image.size)) }.pngData() }
您还可以扩展UIImage以返回灰度图像:
extension UIImage { var ciImage: CIImage? { CIImage(image: self) } func grayscale(isOpaque: Bool = false) -> UIImage? { guard let ciImage = ciImage?.applyingFilter("CIColorControls", parameters: [kCIInputSaturationKey: 0]) else { return nil } let format = imageRendererFormat format.opaque = isOpaque return UIGraphicsImageRenderer(size: size, format: format).image { _ in UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size)) } } }
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 }