Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy an image to MacOS clipboard using python

Tags:

I want to copy an image (PIL image) to clipboard on Mac OS I tried dozens of different ways to do that. Most of python clipboard modules like pyclip or clipboard doesn't support images.

I found a code that does that on windows, but nothing for mac. I tried to use QT, installed it through brew, for some reason brew installed a new python 3.7.2 (I had 3.7.1) and messed up with terminal commands like python and python3. I managed to fix it, but it's very frustrating. And I couldn't get it to work anyway.

I've seen a method with win32 clipboard, but it's for windows only. I tried various different modules, but none of them accept images. I couldn't come up with a solution, so I'm here asking for help.

A little background. I'm writing an app that will save the image from the clipboard and saves it to a file. I have no problem with this, but I also want to store what I saved and later to be able to pull it back to the clipboard. Like Open Last Saved.

like image 205
irondsd Avatar asked Jan 02 '19 14:01

irondsd


People also ask

How do I copy an image to my clipboard on a Mac?

To copy a portion of the screen to the clipboard, press Command-Control-Shift-4. A cross-hair cursor will appear and you can click and drag to select the area you wish to capture. When you release the mouse button, you can paste the screen shot to another application.

How do I create a clipboard from a JPEG on a Mac?

Steps to save clipboard images on a mac:Launch the Preview app on your mac. Click on the File tab of the Preview app menu. Click Export. Click on Format and select either JPG or PNG as the file type.

How do I get an image from the clipboard in Python?

In Python, you can get the image from the clipboard with the ImageGrab. grabclipboard() function in Pillow(PIL). As of version 9.1. 0 (April 2022), it is available only for Windows and macOS.


1 Answers

This little piece of ugliness works and loads "image.jpg" onto the clipboard...

#!/usr/bin/env python3

import subprocess

subprocess.run(["osascript", "-e", 'set the clipboard to (read (POSIX file "image.jpg") as JPEG picture)'])
like image 159
Mark Setchell Avatar answered Oct 05 '22 00:10

Mark Setchell