ProcessThumbnal.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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: ["JPG", "jpg"]).contains(NSString(string: filePath).pathExtension) {
  20. return true
  21. }
  22. if NSArray(array: ["bmp", "BMP", "PNG", "png", "JPG", "jpg"]).contains(NSString(string: filePath).pathExtension) {
  23. let imageSource = CGImageSourceCreateWithURL(URL.init(fileURLWithPath: filePath, isDirectory: false) as CFURL, nil)
  24. if nil == imageSource {
  25. return false
  26. }
  27. // Get the BMP image
  28. let cgimage = CGImageSourceCreateImageAtIndex(imageSource!, 0, nil)
  29. if nil == cgimage {
  30. return false
  31. }
  32. let rep = NSBitmapImageRep.init(cgImage: cgimage!)
  33. let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [:]);
  34. let url = URL.init(fileURLWithPath: desPath, isDirectory: false)
  35. try? data!.write(to: url)
  36. return true
  37. }
  38. var didFinished = false
  39. let semaphore = DispatchSemaphore(value: 0)
  40. let url = URL.init(fileURLWithPath: filePath, isDirectory: false)
  41. generator.generateRepresentations(for: QLThumbnailGenerator.Request.init(fileAt: url, size: outputSize, scale: 2.0, representationTypes: QLThumbnailGenerator.Request.RepresentationTypes.thumbnail),
  42. update: { (representation, type, error) in
  43. if nil != representation {
  44. let image = representation!.nsImage as NSImage
  45. if nil != image {
  46. didFinished = true
  47. let rep = NSBitmapImageRep.init(cgImage: image.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
  48. let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [:]);
  49. let url = URL.init(fileURLWithPath: desPath, isDirectory: false)
  50. try? data!.write(to: url)
  51. }
  52. }
  53. semaphore.signal()
  54. })
  55. semaphore.wait()
  56. return didFinished
  57. }
  58. }