将 CGImageRef 保存为 png 文件?
在我的 Cocoa 应用程序中,我从磁盘加载一个 .jpg 文件,并对其进行操作。现在需要将其作为 .png 文件写入磁盘。你怎么能这么做呢?
感谢您的帮助!
in my Cocoa application, I load a .jpg file from disk, manipulate it. Now it needs to be written to disk as a .png file. How can you do that?
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 CGImageDestination 并传递 kUTTypePNG 是正确的方法。以下是一个快速片段:
您需要将
ImageIO
和CoreServices
(或 iOS 上的MobileCoreServices
)添加到项目中并包含标头。如果您使用的是 iOS 并且不需要适用于 Mac 的解决方案,则可以使用更简单的方法:
在我的测试中,ImageIO 方法比 UIImage 方法快大约 10%我的 iPhone 5s。在模拟器中,UIImage 方法更快。如果您确实关心性能,那么可能值得针对您在设备上的特定情况进行测试。
Using
CGImageDestination
and passingkUTTypePNG
is the correct approach. Here's a quick snippet:You'll need to add
ImageIO
andCoreServices
(orMobileCoreServices
on iOS) to your project and include the headers.If you're on iOS and don't need a solution that works on Mac too, you can use a simpler approach:
In my tests, the ImageIO approach was about 10% faster than the UIImage approach on my iPhone 5s. In the simulator, the UIImage approach was faster. It's probably worth testing each for your particular situation on the device if you're really concerned with performance.
这是 macOS 友好的 Swift 3 & 4 示例:
Here is a macOS-friendly, Swift 3 & 4 example:
创建一个
CGImageDestination
,传递kUTTypePNG
作为要创建的文件类型。添加图像,然后最终确定目的地。Create a
CGImageDestination
, passingkUTTypePNG
as the type of file to create. Add the image, then finalize the destination.Swift 5+采用版本
Swift 5+ adopted version
提供的解决方案可能仍然可以正常工作,但有一些更新的 API CoreImage 中的 this 具有相同的功能,并且使用起来更加“Swifty”:
The provided solutions probably still work fine but there is some newer API for this in
CoreImage
which does the same and is a bit more "Swifty" to use: