Browse Source

综合 - 修复AI模块开启图片文件时,会先将图片格式转为JPG后再去处理

wanjun 1 year ago
parent
commit
7fb75af8c1

+ 46 - 2
PDF Office/PDF Master/Class/Home/ViewController/KMAIOpenPDFFilesVC.swift

@@ -87,6 +87,48 @@ class KMAIOpenPDFFilesVC: NSViewController {
     
     // MARK: Private Methods
     
+    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
+    }
+    
     func openImageFile(url: URL) -> Void {
         let filePath = url.path
         
@@ -108,9 +150,11 @@ class KMAIOpenPDFFilesVC: NSViewController {
         let document = CPDFDocument.init()
         var success = false
         
+        let jpgPath = self.imageToJPG(filePath: filePath, savePath: savePath)
+
         //FIXME: 无法插入图片
-        let image = NSImage(contentsOfFile: filePath)
-        let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
+        let image = NSImage(contentsOfFile: jpgPath)
+        let insertPageSuccess = document?.insertPage(image!.size, withImage: jpgPath, at: document!.pageCount)
         if insertPageSuccess != nil {
             //信号量控制异步
             let semaphore = DispatchSemaphore(value: 0)