如何在Swift 4中压缩NSImage

时间:2018-10-08 19:53:41

标签: cocoa swift4 nsimage

我正在开发Mac OS的应用程序,无法为compressing NSImage找到任何方法并将它们转换为Swift 4的base64编码字符串。

我几乎找不到 Swift3代码

 func compressUnderMegaBytes(megabytes: CGFloat) -> NSImage? {
        var compressionRatio = 1.0
        var imageRep = NSBitmapImageRep(data: self.tiffRepresentation!)
        var options = NSDictionary(object: NSNumber(floatLiteral: compressionRatio), forKey: NSBitmapImageRep.PropertyKey.compressionFactor as NSCopying)
        var compressedData: Data? = imageRep?.representation(using: .jpeg, properties: options as! [NSBitmapImageRep.PropertyKey : Any])
        while compressedData?.length > (megabytes * 1024 * 1024) {
            compressionRatio = compressionRatio * 0.9
            options = NSDictionary(object: NSNumber(floatLiteral:compressionRatio), forKey: NSBitmapImageRep.PropertyKey.compressionFactor as NSCopying)
            compressedData = imageRep?.representation(using:.png, properties: options as! [NSBitmapImageRep.PropertyKey : Any])
            if compressionRatio <= 0.4 {
                break
            }
        }
        return NSImage(data: compressedData!)
    }

但转换为Swift 4后出现以下错误

enter image description here

1 个答案:

答案 0 :(得分:1)

翻译后的代码非常繁琐。在Swift 4中不需要NSDictionary 绕行

length已重命名为count

extension NSImage {
    func compressUnderMegaBytes(megabytes: CGFloat) -> NSImage? {

        var compressionRatio = 1.0
        guard let tiff = self.tiffRepresentation, let imageRep = NSBitmapImageRep(data: tiff) else { return nil }
        var compressedData = imageRep.representation(using: .jpeg, properties: [.compressionFactor : compressionRatio])!
        while CGFloat(compressedData.count) > megabytes * 1024 * 1024 {
            compressionRatio = compressionRatio * 0.9
            compressedData = imageRep.representation(using: .png, properties:  [.compressionFactor : compressionRatio])!
            if compressionRatio <= 0.4 {
                break
            }
        }
        return NSImage(data: compressedData)
    }
}

或者没有不安全的未包装可选内容

extension NSImage {
    func compressUnderMegaBytes(megabytes: CGFloat) -> NSImage? {

        var compressionRatio = 1.0
        guard let tiff = self.tiffRepresentation, let imageRep = NSBitmapImageRep(data: tiff) else { return nil }
        var compressedData = imageRep.representation(using: .jpeg, properties: [.compressionFactor : compressionRatio])
        if compressedData == nil { return self }
        while CGFloat(compressedData!.count) > megabytes * 1024 * 1024 {
            compressionRatio = compressionRatio * 0.9
            let newCompressedData = imageRep.representation(using: .png, properties:  [.compressionFactor : compressionRatio])
            if compressionRatio <= 0.4 || newCompressedData == nil {
                break
            }
            compressedData = newCompressedData
        }
        return NSImage(data: compressedData!)
    }
}

注意:是否打算将第一次压缩为jpg,然后压缩为png