createCGImage 在尝试使用 CIFilter 旋转/裁剪图像时返回 nil



我正在努力将多个CIFilter应用于图像,但是当我应用第二个过滤器时,我总是得到零结果。我创建了裁剪和旋转函数,如下所示:

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
}
如果我先应用裁剪然后旋转,

我的上下文.createCGImage工作正常,但是当我应用旋转然后裁剪时,它返回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,因此裁剪矩形确实超出了范围,使裁剪函数返回0x0大小的图像。我添加了一个翻译以使原点返回到 0,0,一切正常。类似的问题在这里:核心映像:使用 CICrop 后,应用合成过滤器不起作用

我创建的翻译功能:

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}

相关内容

  • 没有找到相关文章

最新更新