Created
February 15, 2018 20:14
-
-
Save phawk/3346528a624fec7bbbae8330a15f8666 to your computer and use it in GitHub Desktop.
Swift macOS generate image previews of files on disk
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 characters
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") | |
} | |
} |
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 characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NSImage+QuickLook original taken from https://github.com/incbee/NSImage-QuickLook and ported to swift4