|
@@ -104,6 +104,25 @@ class KMImageOptimization: NSObject {
|
|
|
return compressedData
|
|
|
}
|
|
|
|
|
|
+ static func resizeImage(_ image: NSImage, toSize newSize: NSSize) -> Data? {
|
|
|
+ let resizedImage = NSImage(size: newSize)
|
|
|
+
|
|
|
+ resizedImage.lockFocus()
|
|
|
+ NSGraphicsContext.current?.imageInterpolation = .high
|
|
|
+
|
|
|
+ image.draw(in: NSRect(x: 0, y: 0, width: newSize.width, height: newSize.height), from: NSRect.zero, operation: .copy, fraction: 1.0)
|
|
|
+
|
|
|
+ resizedImage.unlockFocus()
|
|
|
+
|
|
|
+ guard let imageData = resizedImage.tiffRepresentation,
|
|
|
+ let bitmapImage = NSBitmapImageRep(data: imageData),
|
|
|
+ let compressedData = bitmapImage.representation(using: .png, properties: [:]) else {
|
|
|
+ return nil
|
|
|
+ }
|
|
|
+
|
|
|
+ return compressedData
|
|
|
+ }
|
|
|
+
|
|
|
static func needCompressImageLosslessly(image: NSImage, targetSize: CGSize, maxSizeInBytes: Int, targetCompression: CGFloat) -> String {
|
|
|
let kFilePath: NSString = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path + "KMImageOptimizationCache" as NSString
|
|
|
let string: NSString = (kFilePath as String) + "/" + "optimization.png" as NSString
|
|
@@ -126,6 +145,18 @@ class KMImageOptimization: NSObject {
|
|
|
print("保存图像失败:\(error)")
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+// // 示例用法
|
|
|
+// if let compressedData = KMImageOptimization.resizeImage(image, toSize: targetSize) {
|
|
|
+// let saveURL = URL(fileURLWithPath: string as String)//URL(fileURLWithPath: "/path/to/save/compressed_image.png")
|
|
|
+// do {
|
|
|
+// try compressedData.write(to: saveURL)
|
|
|
+// // 图像已成功保存在指定路径中
|
|
|
+// print("保存图像成功:\(string)")
|
|
|
+// } catch {
|
|
|
+// print("保存图像失败:\(error)")
|
|
|
+// }
|
|
|
+// }
|
|
|
return string as String
|
|
|
}
|
|
|
}
|