UIImage to CIImage to UIImage results in pngData returning nil on iOS 12

守給你的承諾、 提交于 2020-12-13 17:59:15

问题


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?


回答1:


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.

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);

This should work consistently in any iOS version.



来源:https://stackoverflow.com/questions/59320866/uiimage-to-ciimage-to-uiimage-results-in-pngdata-returning-nil-on-ios-12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!