Created
February 15, 2018 20:14
-
-
Save phawk/3346528a624fec7bbbae8330a15f8666 to your computer and use it in GitHub Desktop.
Revisions
-
Pete Hawkins created this gist
Feb 15, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 } } } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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") } }