Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write image to Windows clipboard in python with PIL and win32clipboard?

I'm trying to open an image file and copy the image to the Windows clipboard. Is there a way to fix this:

import win32clipboard
from PIL import Image

def send_to_clipboard(clip_type, data): 
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(clip_type, data) 
    win32clipboard.CloseClipboard()

clip_type = win32clipboard.CF_BITMAP
filepath = 'c:\\temp\\image.jpg'

im = Image.open(filepath) 
data = im.tobitmap() # fails with valueerror: not a bitmap
# data = im.tostring() runs, but receiving programs can't read the results
send_to_clipboard(clip_type, data)

I could install PythonMagick, etc., but would prefer not installing yet another library for a one-off program

like image 810
foosion Avatar asked Aug 13 '11 12:08

foosion


3 Answers

from cStringIO import StringIO
import win32clipboard
from PIL import Image

def send_to_clipboard(clip_type, data):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(clip_type, data)
    win32clipboard.CloseClipboard()

filepath = 'image.jpg'
image = Image.open(filepath)

output = StringIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()

send_to_clipboard(win32clipboard.CF_DIB, data)
like image 78
cgohlke Avatar answered Nov 14 '22 16:11

cgohlke


The file header off-set of BMP is 14 bytes. Well, BMP is also known as the device independent bitmap (DIB) file format, so you don't need to worried about the magic number 14.

FYI, it does need a windows clipboard API. Hence you can use BMP but can't use

image.convert("RGB").save(output, "PNG")
data = output.getvalue()[8:]

even you know the offset is 8 for PNG.

like image 1
yfyang Avatar answered Nov 14 '22 16:11

yfyang


This worked for me in Python 3.8 (solution found here)

It's the same answer as the cgohike's but:

output = StringIO()

changed into:

output = io.BytesIO()

Full code:

import io
import win32clipboard
from PIL import Image

def send_to_clipboard(clip_type, data):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(clip_type, data)
    win32clipboard.CloseClipboard()

image = Image.open('image.jpg')

output = io.BytesIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()

send_to_clipboard(win32clipboard.CF_DIB, data)
like image 1
deshu Avatar answered Nov 14 '22 18:11

deshu