Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@phawk phawk commented Feb 15, 2018

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

@fukemy

This comment has been minimized.

Copy link

@fukemy 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