Skip to content

Instantly share code, notes, and snippets.

@phawk
Created February 15, 2018 20:14
Show Gist options
  • Select an option

  • Save phawk/3346528a624fec7bbbae8330a15f8666 to your computer and use it in GitHub Desktop.

Select an option

Save phawk/3346528a624fec7bbbae8330a15f8666 to your computer and use it in GitHub Desktop.

Revisions

  1. Pete Hawkins created this gist Feb 15, 2018.
    34 changes: 34 additions & 0 deletions NSImage+QuickLook.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    import AppKit
    import QuickLook

    extension NSImage {
    static func previewForFile(path fileURL: URL, ofSize size: CGSize, asIcon: Bool) -> NSImage? {

    let dict = [
    kQLThumbnailOptionIconModeKey: NSNumber(booleanLiteral: asIcon)
    ] as CFDictionary


    let ref = QLThumbnailImageCreate(kCFAllocatorDefault, fileURL as CFURL, size, dict)

    if let cgImage = ref?.takeUnretainedValue() {
    // Take advantage of NSBitmapImageRep's -initWithCGImage: initializer, new in Leopard,
    // which is a lot more efficient than copying pixel data into a brand new NSImage.
    // Thanks to Troy Stephens @ Apple for pointing this new method out to me.
    let bitmapImageRep = NSBitmapImageRep.init(cgImage: cgImage)
    let newImage = NSImage.init(size: bitmapImageRep.size)
    newImage.addRepresentation(bitmapImageRep)

    ref?.release()

    return newImage
    } else {
    // If we couldn't get a Quick Look preview, fall back on the file's Finder icon.
    let icon = NSWorkspace.shared.icon(forFile: fileURL.path)

    icon.size = size

    return icon
    }
    }
    }
    17 changes: 17 additions & 0 deletions generateImagePreview.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    func generatePreview() {
    guard let fileURL = upload?.fileURL else { return }

    do {
    let values = try fileURL.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey])

    if let type = values.typeIdentifier,
    UTTypeConformsTo(type as CFString, kUTTypeImage) {
    if let imageData = FileManager.default.contents(atPath: fileURL.path) {
    self.imagePreview.image = NSImage(data: imageData)
    }
    }
    }
    catch {
    Logger.error("Failed to lookup resource values")
    }
    }