ProcessThumbnal.swift 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // ProcessThumbnal.swift
  3. // ProcessCheckFile
  4. //
  5. // Created by 朱东勇 on 2022/12/9.
  6. //
  7. import Foundation
  8. import QuickLook
  9. import QuickLookUI
  10. import QuickLookThumbnailing
  11. import ImageIO
  12. let generator = QLThumbnailGenerator.shared
  13. class ProcessThumbnal : NSObject {
  14. class func process(_ filePath:String, desPath:String) -> Bool {
  15. let kDefaultThumbnailSize = CGSizeMake(1000.0, 1000.0)
  16. return process(filePath, desPath: desPath, outputSize: kDefaultThumbnailSize)
  17. }
  18. class func process(_ filePath:String, desPath:String, outputSize:CGSize) -> Bool {
  19. if NSArray(array: ["PDF", "pdf"]).contains(NSString(string: filePath).pathExtension) {
  20. return autoreleasepool {
  21. let status = FileConverter.shared().converter(filePath, inDesPath: desPath)
  22. return status == 1
  23. }
  24. }
  25. if NSArray(array: ["JPG", "jpg"]).contains(NSString(string: filePath).pathExtension) {
  26. return true
  27. }
  28. if NSArray(array: ["bmp", "BMP", "PNG", "png", "JPG", "jpg"]).contains(NSString(string: filePath).pathExtension) {
  29. return autoreleasepool {
  30. let imageSource = CGImageSourceCreateWithURL(URL.init(fileURLWithPath: filePath, isDirectory: false) as CFURL, nil)
  31. if nil == imageSource {
  32. return false
  33. }
  34. // Get the BMP image
  35. let cgimage = CGImageSourceCreateImageAtIndex(imageSource!, 0, nil)
  36. if nil == cgimage {
  37. return false
  38. }
  39. let rep = NSBitmapImageRep.init(cgImage: cgimage!)
  40. let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [:]);
  41. let url = URL.init(fileURLWithPath: desPath, isDirectory: false)
  42. try? data!.write(to: url)
  43. return true
  44. }
  45. }
  46. var didFinished = false
  47. let semaphore = DispatchSemaphore(value: 0)
  48. let url = URL.init(fileURLWithPath: filePath, isDirectory: false)
  49. generator.generateRepresentations(for: QLThumbnailGenerator.Request.init(fileAt: url, size: outputSize, scale: 2.0, representationTypes: QLThumbnailGenerator.Request.RepresentationTypes.thumbnail),
  50. update: { (representation, type, error) in
  51. if nil != representation {
  52. autoreleasepool {
  53. let image = representation!.nsImage as NSImage
  54. if nil != image {
  55. didFinished = true
  56. let rep = NSBitmapImageRep.init(cgImage: image.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
  57. let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [:]);
  58. let url = URL.init(fileURLWithPath: desPath, isDirectory: false)
  59. try? data!.write(to: url)
  60. }
  61. }
  62. }
  63. semaphore.signal()
  64. })
  65. semaphore.wait()
  66. return didFinished
  67. }
  68. }