ios - 从 CIImage 获取 CGImage

标签 ios core-graphics core-image cgimage ciimage

我有一个从 CIImage 加载的 UIImage:

tempImage = [UIImage imageWithCIImage:ciImage];

问题是我需要将 tempImage 裁剪为特定的 CGRect,我知道如何做到这一点的唯一方法是使用 CGImage . 问题是在 iOS 6.0 文档中我发现了这个:

CGImage
如果 UIImage 对象是使用 CIImage 对象初始化的,则该属性的值为 NULL。

一个。如何从 CIImage 转换为 CGImage? 我正在使用这段代码,但我有内存泄漏(并且无法理解在哪里):

+(UIImage*)UIImageFromCIImage:(CIImage*)ciImage {  
    CGSize size = ciImage.extent.size;  
    UIGraphicsBeginImageContext(size);  
    CGRect rect;  
    rect.origin = CGPointZero;  
    rect.size   = size;  
    UIImage *remImage = [UIImage imageWithCIImage:ciImage];  
    [remImage drawInRect:rect];  
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext();  
    remImage = nil;  
    ciImage = nil;  
    //
    return result;  
}

最佳答案

Swift 3Swift 4Swift 5

这是一个很好的小函数,可以在 Swift 中将 CIImage 转换为 CGImage

func convertCIImageToCGImage(inputImage: CIImage) -> CGImage? {
    let context = CIContext(options: nil)
    if let cgImage = context.createCGImage(inputImage, from: inputImage.extent) {
        return cgImage
    }
    return nil
}

注意事项:

  • CIContext(options: nil) 将使用软件渲染器并且可能非常慢。要提高性能,请使用 CIContext(options: [CIContextOption.useSoftwareRenderer: false]) - 这会强制操作在 GPU 上运行,并且可以更快。
  • 如果您多次使用 CIContext,请按照 apple 的建议将其缓存。

关于ios - 从 CIImage 获取 CGImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14402413/

相关文章:

ios - 用核心图形绘制一个羽毛状的圆圈

ios - 具有自定义 Metal 内核的核心图像过滤器不起作用

macos - CIImageAccumulator 的作用是什么?

ios - 如果我将自动释放的对象桥接到 Core Foundation,我必须使用 __bridge 或 __bridge_retained 吗?

ios - 如何在Xcode中平滑移动光标?

iphone - 如何使用 UIPanGestureRecognizer 中的 velocityView 加快拖动速度?

iphone - 如何用颜色填充形状

ios - 不停止定时器,重新启动: will it cause running multiple timers in swift

ios - Alamofire Swift HTTPPost 登录和 JSON 响应

ios - 如何使用 Depth Api 去除肖像背景?