gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:59:33 27 4
gpt4 key购买 nike

我正在对图像应用多个 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 工作正常,但是当我应用旋转然后裁剪时,它返回 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 并且一切正常。类似问题在这里: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}

关于ios - 尝试使用 CIFilter 旋转/裁剪图像时,createCGImage 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47031495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com