blog icon indicating copy to clipboard operation
blog copied to clipboard

How to create Quick look thumbnail for files

Open onmyway133 opened this issue 1 year ago • 0 comments

Use QuickLookThumbnailing framework

import AppKit
import QuickLookThumbnailing

actor QuicklookService {
    static let shared = QuicklookService()
    
    private let generator = QLThumbnailGenerator.shared
    
    func image(
        fileUrl: URL,
        size: CGSize
    ) async -> NSImage {
        let scale = NSScreen.main?.backingScaleFactor ?? 2
        let request = QLThumbnailGenerator.Request(
            fileAt: fileUrl,
            size: size,
            scale: scale,
            representationTypes: .thumbnail
        )
        
        do {
            let representation = try await generator.generateBestRepresentation(for: request)
            return representation.nsImage
        } catch {
            return NSWorkspace.shared.icon(forFile: fileUrl.path)
        }
    }
}

Read more

onmyway133 avatar May 13 '23 05:05 onmyway133