Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

python - Copy image to clipboard?

First of all, the question on SO copy image to clipboard in python leads to answer Write image to Windows clipboard in python with PIL and win32clipboard?, which was only good for Python 2.x. -- I tried it and it didn't work. I overcame one problem: StringIO and cStringIO modules are gone in Python 3.0:, but bumped into another one:

TypeError: string argument expected, got 'bytes'

Hence, re-asking the same question again for Python 3 -- How to copy image to clipboard in Python 3? Here is the code I've got so far:

from io 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)

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't want StringIO here. Images are raw binary data, and in Py3, str is purely for text, bytes and bytes-like objects (bytearray, contiguous memoryviews, mmaps) are for binary data. To replace Py2's StringIO.StringIO for binary data, you want to use io.BytesIO in Python 3, not io.StringIO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...