Advertisement
asweigart

macOS image copy

Aug 2nd, 2023
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. from PIL import Image
  2. from Quartz import NSPasteboard, NSPasteboardTypeTIFF
  3. from Cocoa import NSImage, NSBitmapImageRep
  4. import io
  5.  
  6. def send_to_clipboard(image):
  7. # Convert the Pillow image object to TIFF format
  8. output = io.BytesIO()
  9. image.save(output, format="TIFF")
  10. tiff_data = output.getvalue()
  11. output.close()
  12.  
  13. # Create an NSImage from the TIFF data
  14. ns_image = NSImage.alloc().initWithData_(tiff_data)
  15.  
  16. # Create a bitmap representation
  17. image_rep = NSBitmapImageRep.alloc().initWithData_(tiff_data)
  18.  
  19. # Set the image to the clipboard
  20. pasteboard = NSPasteboard.generalPasteboard()
  21. pasteboard.declareTypes_owner_([NSPasteboardTypeTIFF], None)
  22. pasteboard.setData_forType_(image_rep.TIFFRepresentation(), NSPasteboardTypeTIFF)
  23.  
  24. # Open an image using Pillow
  25. image_path = 'example.png'
  26. image = Image.open(image_path)
  27.  
  28. # Send the image to clipboard
  29. send_to_clipboard(image)
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement