我环顾 CoreImage 框架过滤器,我发现 CIColorMatrix 可以工作。
extension UIImage {
func colorized(with color: UIColor) -> UIImage? {
guard
let ciimage = CIImage(image: self),
let colorMatrix = CIFilter(name: "CIColorMatrix")
else { return nil }
var r: CGFloat = 1, g: CGFloat = 1, b: CGFloat = 1, a: CGFloat = 1
color.getRed(&r, green: &g, blue: &b, alpha: &a)
colorMatrix.setDefaults()
colorMatrix.setValue(ciimage, forKey: "inputImage")
colorMatrix.setValue(CIVector(x: 1, y: 0, z: 0, w: 0), forKey: "inputRVector")
colorMatrix.setValue(CIVector(x: 0, y: 1, z: 0, w: 0), forKey: "inputGVector")
colorMatrix.setValue(CIVector(x: 0, y: 0, z: 1, w: 0), forKey: "inputBVector")
colorMatrix.setValue(CIVector(x: 0, y: 0, z: 0, w: 1), forKey: "inputAVector")
colorMatrix.setValue(CIVector(x: -r, y: -g, z: -b, w: 0), forKey: "inputBiasVector")
if let ciimage = colorMatrix.outputImage {
return UIImage(ciImage: ciimage)
}
return nil
}
}
let image = oriimage.colorized(with: color) ?? oriimage
let screensize:CGSize = CGSize(width: 720, height: 1280)
var face = image.cropped(boundingBox: facerect)
var left = image.cropped(boundingBox: leftrect)
var right = image.cropped(boundingBox: rightrect)
let col = 64,row = 64,c=3
face = face.resizeImageWith(newSize: CGSize(width:col,height:row))
但是,另一个问题出现在最后一行。结果返回 nil 并停止应用程序,但是当我显示图像时,图像很好。