gpt4 book ai didi

cocoa - 如何在 Swift 4 中压缩 NSImage

转载 作者:行者123 更新时间:2023-12-03 17:46:55 28 4
gpt4 key购买 nike

我正在为 Mac OS 开发应用程序,我无法找到任何压缩 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

最佳答案

翻译后的代码相当繁琐。 NSDictionary detour 在 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

关于cocoa - 如何在 Swift 4 中压缩 NSImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52709210/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com