8

Is there any way to get the quick look preview image for a file?

I'm looking for something like this:

NSImage *image = [QuickLookPreviewer quickLookPreviewForFile:path];

mirkokiefer
  • 3,347
  • 4
  • 20
  • 25
Greg
  • 9,068
  • 6
  • 49
  • 91

2 Answers2

6

See QLThumbnailRequest in the docs: https://developer.apple.com/library/mac/#documentation/UserExperience/Reference/QLThumbnailRequest_Ref/Reference/reference.html

NSURL *path = aFileUrl;

NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kQLThumbnailOptionIconModeKey];

CGImageRef ref = QLThumbnailImageCreate(kCFAllocatorDefault, (CFURLRef)path, CGSizeMake(600, 800 /* Or whatever size you want */), (CFDictionaryRef)options);
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Greg
  • 9,068
  • 6
  • 49
  • 91
2

In Swift I ended up with something like this (the force unwraps should be replaced):

let options = [
  kQLThumbnailOptionIconModeKey: false
]

let ref = QLThumbnailCreate(
  kCFAllocatorDefault,
  url as NSURL,
  CGSize(width: 150, height: 150),
  options as CFDictionary
)

let thumbnail = ref!.takeRetainedValue()
let cgImageRef = QLThumbnailCopyImage(thumbnail)
let cgImage = cgImageRef!.takeRetainedValue()
let image = NSImage(cgImage: cgImage, size: CGSize(width: cgImage.width, height: cgImage.height))
mirkokiefer
  • 3,347
  • 4
  • 20
  • 25
  • 1
    I’m pretty sure you want to use `takeRetainedValue()` in both places you’ve used `takeUnretainedValue()` because the `Create` and `Copy` functions both return a CFObject with a +1 reference. I think your current code will leak every time it’s called. – Wil Shipley Apr 01 '19 at 12:59
  • 1
    Thanks @WilShipley, I fixed that. – mirkokiefer Apr 26 '19 at 17:41