将CIFilter应用于UIImage会导致调整大小并重新定位图像

时间:2017-04-30 17:35:47

标签: ios swift cifilter ciimage

将CIFilter应用于使用相机拍摄的照片后,拍摄的图像会缩小并重新定位。

我在想,如果我能够获得原始图像的大小和方向,它会相应地缩放并将图像视图固定到屏幕的角落。然而,这种方法没有改变,也没有意识到我可以正确地将图像缩放到屏幕的整个尺寸。

func applyBloom() -> UIImage {
  let ciImage = CIImage(image: image) // image is from UIImageView

  let filteredImage = ciImage?.applyingFilter("CIBloom",
                                              withInputParameters: [ kCIInputRadiusKey: 8,
                                                                     kCIInputIntensityKey: 1.00 ])
  let originalScale = image.scale
  let originalOrientation = image.imageOrientation


  if let image = filteredImage {
    let image = UIImage(ciImage: image, scale: originalScale, orientation: originalOrientation)
    return image
  }

  return self.image
}

图片描述: 照片捕获和图像的屏幕截图,空间距是图像缩小的结果。

enter image description here

2 个答案:

答案 0 :(得分:2)

尝试这样的事情。替换:

func applyBloom() -> UIImage {
    let ciInputImage = CIImage(image: image) // image is from UIImageView
    let ciOutputImage = ciInputImage?.applyingFilter("CIBloom",
                                          withInputParameters: [kCIInputRadiusKey: 8, kCIInputIntensityKey: 1.00 ])
    let context = CIContext()
    let cgOutputImage = context.createCGImage(ciOutputImage, from: ciInputImage.extent)
    return UIImage(cgImage: cgOutputImage!)
}
  • 我保留了各种变量来帮助解释发生了什么。
  • 显然,根据您的代码,可能需要对选项和调整进行一些调整。

发生了什么 - 采取过滤/输出CIImage,并使用CIContext,写入输入CIImage大小的CGImage。

  • 请注意,CIContext很昂贵。如果你已经创建了一个,你应该使用它。
  • 相当多,UIImage size 与CIImage 范围相同。 (我说的很多,因为一些生成的CIImages可以有无限范围。)
  • 根据您的特定需求(和您的UIImageView),您可能希望使用输出CIImage范围。通常,它们是相同的。

最后,一个建议。如果您正在尝试使用CIFilter来显示"接近实时"更改图像(如照片编辑器),考虑使用CIImages获得的主要性能改进,以及GLKView对UIImages和UIImageView的改进。前者使用设备GPU而不是CPU。

答案 1 :(得分:0)

如果CIFilter输出的图像尺寸与输入图像不同(例如,使用CIPixellate),也会发生这种情况

在这种情况下,只需告诉CIContext将图像渲染成较小的矩形即可:

let cgOutputImage = context.createCGImage(ciOutputImage, from: ciInputImage.extent.insetBy(dx: 20, dy: 20))