我正在努力将多个CIFilter应用于图像,但是当我应用第二个过滤器时,我一直得到一个nil结果。我已经创建了裁剪和旋转功能,如下所示:
func crop(_ image: CIImage) -> CIImage?{
let cropRectangle = CGRect(x: 0, y: 0, width: 0.5*image.extent.width, height: 0.5*image.extent.height)
guard let filter = CIFilter(name: "CICrop") else {print("Could not create filter.");return nil}
filter.setValue(image, forKey: "inputImage")
filter.setValue(cropRectangle, forKey: "inputRectangle")
return filter.outputImage
}
func rotate(image: CIImage, rotation: CGFloat) -> CIImage?{
guard let filter = CIFilter(name: "CIAffineTransform") else {print("Unable to generate filter");return nil}
let rotationTransform = CGAffineTransform.init(rotationAngle: rotation)
filter.setValue(image, forKey: "inputImage")
filter.setValue(rotationTransform, forKey: "inputTransform")
return filter.outputImage
}
如果我应用裁剪然后旋转,我的context.createCGImage工作正常,但是当我应用rotate然后裁剪时,它返回nil。我已经检查了我试图裁剪的CIImage上的.extension,以确保裁剪矩形在其范围内。接受想法。以下是我对上述2个功能的调用:
let context = CIContext(options: nil)
guard let ciImage = CIImage(image: #imageLiteral(resourceName: "sample3")) else {fatalError("Error on image generation!")}
guard let ciRotated = self.rotate(image: ciImage, rotation: CGFloat(Double.pi*3/2)) else {print("Could not rotate.");return}
guard let ciCropped = self.crop(ciRotated) else {print("Error cropping.");return}
guard let final = context.createCGImage(ciCropped, from: ciCropped.extent) else {print("Error on CG gen.");return}
答案 0 :(得分:0)
问题是旋转图像的原点不再是0,0,因此裁剪矩形实际上超出界限,使裁剪功能返回0x0大小的图像。我添加了一个翻译,使原点返回0,0,一切正常。 类似的问题:Core Image: after using CICrop, applying a compositing filter doesn't line up
我创建的翻译功能:
func translation(image: CIImage, x: CGFloat, y: CGFloat) -> CIImage?{
guard let filter = CIFilter(name: "CIAffineTransform") else {print("Unable to generate filter"); return nil}
let translate = CGAffineTransform.init(translationX: x, y: y)
filter.setValue(image, forKey: "inputImage")
filter.setValue(translate, forKey: "inputTransform")
return filter.outputImage
}
最后调用此示例:
let context = CIContext(options: nil)
guard let ciImage = CIImage(image: #imageLiteral(resourceName: "sample3")) else {fatalError("Error on image generation!")}
guard let ciRotated = self.rotate(image: ciImage, rotation: CGFloat(Double.pi*3/2)) else {print("Could not rotate.");return}
guard let ciTranslated = self.translation(image: ciRotated, x: 0, y: ciRotated.extent.height) else {print("Unable to translate."); return}
guard let ciCropped = self.crop(ciTranslated) else {print("Error cropping.");return}
guard let final = context.createCGImage(ciCropped, from: ciCropped.extent) else {print("Error on CG gen.");return}