python实现图片粘贴_将图像复制到Python3中的剪贴板

这篇博客介绍了如何在Python3中使用PIL和win32clipboard库将图片复制到剪贴板。作者首先提到旧的Python 2.x解决方案在Python 3中不再适用,然后提供了一个在Python 3中解决此问题的代码示例,通过替换StringIO为BytesIO成功实现了功能。
摘要由CSDN通过智能技术生成

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

解决方案

I did copy the code and replace the StringIO with BytesIO and it worked! (with *.jpg and *.png files) Thank you so much!

from io import BytesIO

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 = 'Ico2.png'

image = Image.open(filepath)

output = BytesIO()

image.convert("RGB").save(output, "BMP")

data = output.getvalue()[14:]

output.close()

send_to_clipboard(win32clipboard.CF_DIB, data)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值