# coding:utf-8
import sys
import traceback
import win32clipboard
from io import BytesIO
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()
def get_image_data(args):
image = Image.open(args)
output = BytesIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:] # Bitmap header size
return data
if __name__ == "__main__:
try:
data = get_image_data(sys.argv[1])
send_to_clipboard(win32clipboard.CF_DIB, data)
except Exception:
traceback.print_exc()
手动复制一张 gif 图,查看两种图片编码会得到如下结果:
import chardet
def test():
try:
with open("1.gif", "rb") as f:
data = f.read()
print(f"get stream from BytesIO", data[:30])
print(chardet.detect(data[:30]))
except Exception as e:
print(str(e))
try:
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
print(f"get stream from windows clipboard", data[:30])
print(chardet.detect(data[:30]))
except Exception as e:
print(str(e))
finally:
win32clipboard.CloseClipboard()
get stream from BytesIO b'GIF89aJ\x03T\x02\xf7\xff\x00\\d_+bV\x18\x18\x1c\xd9\xd2\x9du\xa1\'
{'encoding': 'Windows-1252', 'confidence': 0.73, 'language': ''}
get stream from windows clipboard b'(\x00\x00\x00J\x03\x00\x00T\x02\x00\x00\x01\x00 \x00\x03\x00'
{'encoding': 'ISO-8859-1', 'confidence': 0.73, 'language': ''}
直接对 BytesIO 输出的数据流进行转码 data[14:].decode("Windows-1252").encode("ISO-8859-1") 也解决不了问题。求解
References: