Skip to content

Instantly share code, notes, and snippets.

@phawk
Created February 15, 2018 20:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phawk/3346528a624fec7bbbae8330a15f8666 to your computer and use it in GitHub Desktop.
Save phawk/3346528a624fec7bbbae8330a15f8666 to your computer and use it in GitHub Desktop.
Swift macOS generate image previews of files on disk
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")
}
}
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
}
}
}
@phawk
Copy link
Author

phawk commented Feb 15, 2018

NSImage+QuickLook original taken from https://github.com/incbee/NSImage-QuickLook and ported to swift4

@fukemy
Copy link

fukemy commented Mar 27, 2021

hi, any solution for swift?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment