我目前正在制作照片编辑应用。
当用户选择照片时,它会使用此代码自动将其转换为黑白:
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数据,以便在图像视图中使用/Just 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 coreImage: CIImage? { CIImage(image: self) }
func grayscale(isOpaque: Bool = false) -> UIImage? {
guard let coreImage = coreImage?.applyingFilter("CIColorControls", parameters: [kCIInputSaturationKey: 0]) else { return nil }
let format = imageRendererFormat
format.opaque = isOpaque
return UIGraphicsImageRenderer(size: size, format: format).image { _ in
UIImage(ciImage: coreImage).draw(in: CGRect(origin: .zero, size: size))
}
}
}
let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"https://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
}