UIImage到CIImage到UIImage导致pngData在iOS 12上返回nil [英] UIImage to CIImage to UIImage results in pngData returning nil on iOS 12

查看:75
本文介绍了UIImage到CIImage到UIImage导致pngData在iOS 12上返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从相机拍摄的UIImage.
我想进行一些图像处理,因此将其转换为CIImage.
CIImage * ciImage = [CIImage imageWithCGImage:snappedImage.CGImage];
接下来,我做我的事情,然后将其转换回UIImage:
UIImage * image = [UIImage imageWithCIImage:ciImage];
如果现在,我想将其转换为数据以将其保存到Core Data中,例如:
NSData * data = UIImagePNGRepresentation(image);
数据最终在iOS 12上为零.(在iOS 13上运行,如果我尝试使用UIImageJPEGRepresentation,也会发生同样的事情)

I have an UIImage that I snap from the camera.
I want to do some image manipulations so I transform it to a CIImage.
CIImage *ciImage = [CIImage imageWithCGImage:snappedImage.CGImage];
Next I do my thing, and then transform it back to a UIImage:
UIImage *image = [UIImage imageWithCIImage:ciImage];
If now I want to transform this to data to save it into Core Data for example:
NSData *data = UIImagePNGRepresentation(image);
the data ends up being nil on iOS 12. (works on iOS 13, same thing happens with if I try to use the UIImageJPEGRepresentation)

您知道为什么以及如何解决此问题吗?

Any idea why and how to fix this?

推荐答案

使用 [UIImage imageWithCIImage:] API时,我看到了很多问题.您会看到,当您调用此方法时, CIImage 实际上并未被渲染.生成的 UIImage 仍然只是如何创建结果的食谱".取决于UIImage 的用户是否知道这一点并在需要时触发渲染. UIImageView 似乎知道这一点,但是我发现其他API之间存在很多不一致之处.

I see a lot of problems emerging when using the [UIImage imageWithCIImage:] API. You see, your CIImage is not actually rendered when you call this method. The resulting UIImage is still just a "recipe" for how to create the result. It's up to the user of the UIImage to know that and trigger the rendering if needed. UIImageViews seem to know that, but I saw a lot of inconsistencies across other APIs.

相反,您可以使用 CIContext 并自行执行渲染:

What you can do instead is to use a CIContext and perform the rendering yourself explicitly:

// ideally you create this context once and re-use it because it's an expensive object
CIContext* context = [CIContext context];

CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);

NSData* data = [context PNGRepresentationOfImage:ciImage format:kCIFormatBGRA8 colorSpace:colorSpace options:nil];

CGColorSpaceRelease(colorSpace);

这应该在任何iOS版本中均能正常工作.

This should work consistently in any iOS version.

这篇关于UIImage到CIImage到UIImage导致pngData在iOS 12上返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆