переведенный код довольно громоздок.NSDictionary
объезд не требуется в Swift 4.
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
?