[英]UIImage to CIImage to UIImage results in pngData returning nil on iOS 12
I have an UIImage that I snap from the camera.我有一个从相机拍摄的 UIImage。
I want to do some image manipulations so I transform it to a CIImage.我想做一些图像操作,所以我将它转换为 CIImage。
CIImage *ciImage = [CIImage imageWithCGImage:snappedImage.CGImage];
Next I do my thing, and then transform it back to a UIImage:接下来我做我的事情,然后将其转换回 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)数据在 iOS 12 上最终为零。(适用于 iOS 13,如果我尝试使用 UIImageJPEGRepresentation,也会发生同样的事情)
Any idea why and how to fix this?知道为什么以及如何解决这个问题吗?
I see a lot of problems emerging when using the [UIImage imageWithCIImage:]
API.我看到使用[UIImage imageWithCIImage:]
API 时出现了很多问题。 You see, your CIImage
is not actually rendered when you call this method.你看,当你调用这个方法时,你的CIImage
实际上并没有被渲染。 The resulting UIImage
is still just a "recipe" for how to create the result.生成的UIImage
仍然只是如何创建结果的“配方”。 It's up to the user of the UIImage
to know that and trigger the rendering if needed.由UIImage
的用户知道并在需要时触发渲染。 UIImageView
s seem to know that, but I saw a lot of inconsistencies across other APIs. UIImageView
似乎知道这一点,但我看到其他 API 之间存在很多不一致之处。
What you can do instead is to use a CIContext
and perform the rendering yourself explicitly:您可以做的是使用CIContext
并自己显式执行渲染:
// 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);
This should work consistently in any iOS version.这应该在任何 iOS 版本中始终如一地工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.