从CIImage创建UIImage

10

我正在使用一些CoreImage滤镜处理图像。将滤镜应用于我的输入图像会生成一个名为filterOutputImage的输出图像,其类型为CIImage。

现在我希望显示该图像,并尝试执行以下操作:

self.modifiedPhoto = [UIImage imageWithCIImage:filterOutputImage];
self.photoImageView.image = self.modifiedPhoto;

然而视图为空-没有显示任何内容。

如果我添加打印关于filterOutputImage和self.modifiedPhoto详细信息的日志语句,则这些日志语句向我显示这两个变量似乎都包含合法的图像数据:它们的大小被报告,并且对象不是nil。

所以经过一些搜索,我发现了一个解决方案,需要通过CGImage阶段进行处理,即:

CGImageRef outputImageRef = [context createCGImage:filterOutputImage fromRect:[filterOutputImage extent]];
self.modifiedPhoto = [UIImage imageWithCGImage:outputImageRef scale:self.originalPhoto.scale orientation:self.originalPhoto.imageOrientation];
self.photoImageView.image = self.modifiedPhoto;
CGImageRelease(outputImageRef);

这种第二种方法是可行的:我成功地显示了正确的图像。

请问有人能解释一下为什么我的第一次尝试失败了吗?我在使用imageWithCIImage方法时是否做错了什么,导致生成了一个似乎存在但无法显示的图像?是否总是需要"通过"CGImage阶段来从CIImage生成UIImage?

希望有人能解决我的困惑:)

H.

2个回答

18

这应该就可以了!

-(UIImage*)makeUIImageFromCIImage:(CIImage*)ciImage
{
    self.cicontext = [CIContext contextWithOptions:nil];
    // finally!
    UIImage * returnImage;

    CGImageRef processedCGImage = [self.cicontext createCGImage:ciImage 
                                                       fromRect:[ciImage extent]];

    returnImage = [UIImage imageWithCGImage:processedCGImage];
    CGImageRelease(processedCGImage);

    return returnImage;
}

9
我假设 self.photoImageView 是一个 UIImageView?如果是这样,最终它会在 UIImage 上调用 -[UIImage CGImage],然后将该 CGImage 作为 CALayer 的 contents 属性传递。
(请参见注释:我的细节是错误的)
根据 UIImage 文档中的 -[UIImage CGImage] 描述:
If the UIImage object was initialized using a CIImage object, the
value of the property is NULL.

因此,UIImageView调用-CGImage,但结果为NULL,因此没有显示任何内容。
我尚未尝试过这一点,但您可以尝试创建自定义UIView,然后在-[UIView drawRect:]中使用UIImage的-draw...方法来绘制CIImage。

啊!谢谢。是的,photoImageView是一个UIImageView。我不知道它使用UIImage的CGImage属性。 - Hamster
还有一个问题,UIImageView如何显示其图像在哪个文档中有解释?我正在尝试找出你是从哪里学到的 :) - Hamster
实际上,现在我仔细查看二进制代码后发现:UIImageView 重写了 -drawRect: 方法,而不是在自己的 CALayer 上调用 setContents: 方法。看起来它最终会调用 UIImage 的绘制方法,获取 CGImageRef 并将其绘制出来。因此,结果相同,但我的细节描述有误。 - iccir
class-dump 也有帮助。- [UIImageView drawRect:] 的存在对我来说是一个巨大的提示,让我知道我的原始陈述关于内容是错误的。 - iccir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接