所以,这就是我需要的:
- 拍摄一个
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/