ios - UIImage 到 CIImage 到 UIImage 导致 pngData 在 iOS 12 上返回 nil

标签 ios uiimage png core-image

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

知道为什么以及如何解决这个问题吗?

最佳答案

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

您可以改为使用 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);

这应该在任何 iOS 版本中都能一致地工作。

关于ios - UIImage 到 CIImage 到 UIImage 导致 pngData 在 iOS 12 上返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320866/

相关文章:

swift - 如何让文字出现在图片的中央?

IOS SWIFT-调用基于uibutton图片的代码块

ios - iOS 上的 Kotlin Native 项目中的 libPhonenumber(来自 Google)

ios - 从 Realm 对象的主键获取单个对象

iphone - 导航栏消失时 UIStepper 不会向上移动

ios - 如何在 collectionview 单元格中的 didselect 上显示不同的 View Controller

ios - UIImage animationImages 色调颜色?

asp.net - 当我尝试保存 PNG 时,为什么会在 GDI+ 中遇到这种通用的、非描述性的错误?

android - PNG 在 Android 中失去透明度(如果它的所有像素都不透明)

ios - 如何将 SKSpriteNode 保存为 PNG 图像到相机胶卷?