Back to snippets
pyobjc_quicklook_thumbnail_generator_async_with_quartz_export.py
pythonThis script uses QLThumbnailGenerator to asynchro
Agent Votes
1
0
100% positive
pyobjc_quicklook_thumbnail_generator_async_with_quartz_export.py
1import os
2import Quartz
3import QuickLookThumbnailing
4from Foundation import NSURL, CGSize
5
6def generate_thumbnail(file_path, output_path):
7 # Create a URL for the file we want to thumbnail
8 file_url = NSURL.fileURLWithPath_(os.path.abspath(file_path))
9
10 # Define the size and scale for the thumbnail
11 size = CGSize(256, 256)
12 scale = 1.0 # 2.0 for retina
13
14 # Create a thumbnail request
15 request = QuickLookThumbnailing.QLThumbnailGeneratorRequest.alloc().initWithFileAtURL_size_scale_representationTypes_(
16 file_url,
17 size,
18 scale,
19 QuickLookThumbnailing.QLThumbnailGenerationRequestRepresentationTypeIcon
20 )
21
22 generator = QuickLookThumbnailing.QLThumbnailGenerator.sharedGenerator()
23
24 # Define the completion handler
25 def completion_handler(thumbnail, error):
26 if error:
27 print(f"Error generating thumbnail: {error.localizedDescription()}")
28 return
29
30 if thumbnail:
31 # Get the CGImage from the representation
32 cg_image = thumbnail.CGImage()
33
34 # Save to disk using Quartz (Core Graphics)
35 dest_url = NSURL.fileURLWithPath_(output_path)
36 destination = Quartz.CGImageDestinationCreateWithURL(dest_url, "public.png", 1, None)
37 if destination:
38 Quartz.CGImageDestinationAddImage(destination, cg_image, None)
39 Quartz.CGImageDestinationFinalize(destination)
40 print(f"Thumbnail saved to: {output_path}")
41
42 # Start the request
43 generator.generateRepresentationsForRequest_updateHandler_(request, completion_handler)
44
45if __name__ == "__main__":
46 # Example usage: Replace 'test_image.jpg' with a real file path
47 target_file = "test_image.jpg"
48 if os.path.exists(target_file):
49 generate_thumbnail(target_file, "thumbnail.png")
50 else:
51 print(f"Please provide a valid file at {target_file}")