Skip to content

Use Python to copy pictures to the clipboard

Last Updated on 2020-10-30 by Clay

python
Display Python code on the screen

Introduction

Today I tried to develop my side project, I found I need a function to copy the screenshot picture to system clipboard, so I researched some methods.

So far, I have only tested this method on the Windows operating system. Others OS may have to try to see if they can work properly.

Unfortunately, due to other work to be done next, I don’t know when this side project will be completed.


Use Pillow package to take a screenshot

Using Python package Pillow to take a screenshot is very easy. May be you can refer: Recording with Python —— Provided a sample code

If you are using pywin32 in the first time, you need to use the following command to install:

sudo pip3 install win32clipboard


And we can start to coding.

# -*- coding: utf-8 -*-
import win32clipboard as clip
import win32con
from io import BytesIO
from PIL import ImageGrab


First, import the module we need. ImageGrab() is a function to take the screenshot in Pillow. And win32clipboard can make us to copy the image to our clipboard.

image = ImageGrab.grab()


Use key a to screenshot so that we put the captured full-screen image into the variable image. Remember this is stored in RGB format, if you want to use a module to display such as OpenCV, you need to convert it to BGR.


Copy to clipboard

output = BytesIO()
image.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
output.close()
clip.OpenClipboard()
clip.EmptyClipboard()
clip.SetClipboardData(win32con.CF_DIB, data)
clip.CloseClipboard()


It should be noted here that after OpenClipboard(), emptyClipboard() should be used to empty the clipboard. Otherwise, if something is stored in the original clipboard, an error will occur in our program.

After running the above program, find a place to paste it and you can see our screenshot.


References


Read More

Tags:

Leave a Reply