objective-c - 如何使用 Cocoa 压缩 PNG 图像?

标签 objective-c cocoa png image-optimization

所以,这就是我需要的:

  • 拍摄一个NSImage
  • 尽可能压缩(无损压缩,质量没有明显下降)
  • 将其保存回磁盘

过去,我尝试使用 OptiPNG - 作为编译的二进制文件(并异步获取结果) - 效果很好。

但是,如果我不想要带有外部应用程序的类似终端的解决方案,而是更多 Cocoa 原生的解决方案,该怎么办?

有什么想法吗?

最佳答案

NSImage* image; // your NSImage

// With compression
NSData* data = [image
                TIFFRepresentationUsingCompression:NSTIFFCompressionLZW
                factor:0.5f]; // you can change factor between 0 and 1.0 for preferred compression rate

if (data != nil) {
    NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithData:data];
    if (bitmap != nil) {
        NSData* bitmapData = [bitmap
                              representationUsingType:NSBitmapImageFileTypePNG
                              properties:@{}];
        if (bitmapData != nil) {
            [bitmapData
             writeToFile:<file_path> //path where to save png
             atomically:true];
        }
    }
}

更新:正如评论中提到的,这不会压缩 png。
然而,我在 ShareExtension 中使用了这段代码,它很好地压缩了收到的屏幕截图(如果以普通格式保存,则从 1.1-1.5MB 压缩到使用representationUsingType 的 0.4-0.7MB),并且没有质量损失,就像 OP 所要求的那样。

关于objective-c - 如何使用 Cocoa 压缩 PNG 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12330948/

相关文章:

德尔福2006 : Run-time assignment of PNG to TImage loses alpha transparency

objective-c - 渐进式加载 NSTableView

objective-c - OSX 狮子 : different views in fullscreen and in windowed mode

objective-c - Cocoa,无法以编程方式显示窗口

ios - 更改 tableView 单元格内的 UILabel 框架高度

objective-c - 在自己的应用程序中使用 Yosemite 上的图像编辑扩展

Swift SpriteKit : png image appears black while the game is being run. 我该如何解决这个问题?

unix - 将 png 图像合并到一个 pdf 文件中

ios - 在 iOS 中从 Kinvey 下载文件

ios - 为什么我无法在我的 AppDelegate 中以编程方式更改我的初始 View Controller ?