|
@@ -137,10 +137,12 @@ class KMImageToPDFManager: NSObject {
|
|
|
// document.insert(pdfPage!, at: 0)
|
|
|
// success = document.write(toFile: path)
|
|
|
|
|
|
+ let jpgPath = self.imageToJPG(filePath: filePath, savePath: savePath)
|
|
|
+
|
|
|
//FIXME: 无法插入图片
|
|
|
- let image = NSImage(contentsOfFile: filePath)
|
|
|
+ let image = NSImage(contentsOfFile: jpgPath)
|
|
|
if image != nil {
|
|
|
- let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
|
|
|
+ let insertPageSuccess = document?.insertPage(image!.size, withImage: jpgPath, at: document!.pageCount)
|
|
|
if insertPageSuccess != nil {
|
|
|
print("插入成功")
|
|
|
//信号量控制异步
|
|
@@ -269,4 +271,47 @@ class KMImageToPDFManager: NSObject {
|
|
|
|
|
|
return resultFilePath;
|
|
|
}
|
|
|
+
|
|
|
+ // 图片转PNG
|
|
|
+ func imageToJPG(filePath: String, savePath: String) -> String {
|
|
|
+ if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" ||
|
|
|
+ NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" {
|
|
|
+ let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
|
|
|
+
|
|
|
+ let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg")
|
|
|
+ if (!FileManager.default.fileExists(atPath: jpgPath as String)) {
|
|
|
+ FileManager.default.createFile(atPath: jpgPath as String, contents: nil)
|
|
|
+ }
|
|
|
+
|
|
|
+ // 加载 PNG 图像
|
|
|
+ guard let pngImage = NSImage(contentsOfFile: filePath) else {
|
|
|
+ print("Failed to load PNG image")
|
|
|
+ return filePath
|
|
|
+ }
|
|
|
+
|
|
|
+ // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中
|
|
|
+ let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!)
|
|
|
+ let rect = NSRect(origin: .zero, size: bitmap!.size)
|
|
|
+ bitmap?.draw(in: rect)
|
|
|
+
|
|
|
+ // 将 PNG 图像数据转换为 JPG 图像数据
|
|
|
+ guard let jpgData = bitmap?.representation(using: .jpeg, properties: [:]) else {
|
|
|
+ print("Failed to convert PNG to JPG")
|
|
|
+ return filePath
|
|
|
+ }
|
|
|
+
|
|
|
+ // 保存 JPG 图像数据到文件
|
|
|
+ let fileURL = URL(fileURLWithPath: jpgPath)
|
|
|
+ do {
|
|
|
+ try jpgData.write(to: fileURL)
|
|
|
+ print("JPG image saved successfully")
|
|
|
+ return fileURL.path
|
|
|
+ } catch {
|
|
|
+ print("Failed to save JPG image: \(error.localizedDescription)")
|
|
|
+ return filePath
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return filePath
|
|
|
+ }
|
|
|
}
|