PyObjC Framework QuickLookThumbnailing

12.1 · active · verified Tue Apr 14

PyObjC-framework-quicklookthumbnailing provides Python bindings for Apple's QuickLookThumbnailing framework on macOS, allowing developers to generate high-quality thumbnails for various file types programmatically. It is part of the broader PyObjC project, bridging Python with Objective-C frameworks. The current version is 12.1, with new releases typically following macOS SDK updates and Python version changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a thumbnail for a local file using QLThumbnailGenerator. It creates a dummy text file, requests a thumbnail, saves the generated NSImage as a PNG, and then cleans up. Since QuickLookThumbnailing APIs are asynchronous, it utilizes PyObjCTools.AppHelper to manage the event loop until the thumbnail generation is complete.

import Foundation
from QuickLookThumbnailing import QLThumbnailGenerator
from PyObjCTools import AppHelper
import objc
import os

# Create a dummy file for demonstration
file_path = "/tmp/test_pyobjc_thumbnail.txt"
output_path = "/tmp/pyobjc_thumbnail.png"

with open(file_path, "w") as f:
    f.write("Hello, PyObjC Thumbnailing!")

file_url = Foundation.NSURL.fileURLWithPath_(file_path)

@objc.python_block_into_completion_handler
def completion_handler(thumbnail, error):
    if error:
        print(f"Error generating thumbnail: {error}")
    elif thumbnail:
        # thumbnail is an NSImage. Convert to PNG data and save.
        image_data = thumbnail.TIFFRepresentation()
        image_rep = Foundation.NSBitmapImageRep.imageRepWithData_(image_data)
        if image_rep:
            properties = Foundation.NSDictionary.dictionaryWithObject_forKey_(
                Foundation.NSNumber.numberWithFloat_(1.0), Foundation.NSImageCompressionFactor
            )
            png_data = image_rep.representationUsingType_properties_(
                Foundation.NSPNGFileType, properties
            )
            if png_data:
                png_data.writeToFile_atomically_(output_path, True)
                print(f"Thumbnail saved to {output_path}")
            else:
                print("Could not get PNG representation.")
        else:
            print("Could not create image representation.")
    else:
        print("No thumbnail generated.")
    AppHelper.stopEventLoop() # Stop the event loop after completion

print(f"Generating thumbnail for {file_path}...")

generator = QLThumbnailGenerator.sharedGenerator()
thumbnail_size = Foundation.NSSize(width=256, height=256) # Max size for the thumbnail

generator.generateBestRepresentationForFile_size_completionHandler_(
    file_url,
    thumbnail_size,
    completion_handler
)

AppHelper.runEventLoop()

# Clean up dummy files
if os.path.exists(file_path):
    os.remove(file_path)
if os.path.exists(output_path):
    print(f"Cleaned up {output_path}")

view raw JSON →