如何使用Python在OS剪贴板中添加/获取图像数据? [英] How to add/get image data in the OS clipboard using Python?

查看:110
本文介绍了如何使用Python在OS剪贴板中添加/获取图像数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些Python代码可以编辑图像文件,并且想知道如何

将图像数据添加到操作系统剪贴板并从那里获取数据。



在Python中搜索替换或获取剪贴板 text 的跨平台解决方案时,

有很多简单的答案(例如,使用内置的在


注意:显示的387x388 GIF中的第一个粘贴耗时4秒。





核心点:您必须使用MI ME-Type,以请求图像。

  .clipboard_get(type ='image / png')

已通过'GIF''PNG'和'JPEG'作为源图像数据,使用应用程序 GIMP PyCharm 。如果源应用程序支持 type ='image / png',则您始终会获得'PNG'类型的图像数据。




参考



  • clippboard_get(type =< string>)


    从剪贴板中检索数据。类型指定返回数据的形式,并且应为原子名称,例如STRING或FILE_NAME。在现代X11系统上,类型默认为UTF8_STRING。







数据格式

  0x89 0x50 0x4e 0x47 0xd 0xa 0x1a 0xa 0x0 0x0 0x0 0xd 0x49 0x48 0x44 



数据分为用空格分隔的字段;每个字段都转换为它的原子值,并传输32位原子值而不是原子名称。


在删除空白并强制转换后与 int(< field> ;, 0)

  bytearray(b'\ x89PNG\r\n\x1a\n\x00\x00\x00\rIHD ...')
< PIL.PngImagePlugin.PngImageFile image image image = P size = 387x388 at 0xF555E20C> ;




例外:如果根本没有选择或来源应用程序不提供'image / png'

  TclError:CLIPBOARD选择不存在或以 image / png形式存在未定义




  import tkinter as tk 
from PIL import Image,ImageTk
import io


class App(tk.Tk):
def __init __(self):
super().__ init __()#options =(tk.Menu,))
self.menubar = tk.Menu()
self.config(menu = self.menubar)
self.menubar.add_command(label ='paste',command = self.on_paste)

self.label = tk.Label(self,text =剪贴板图像,字体=( David ;,18),
image ='',compound ='center')
self.label.grid(row = 0,column = 0,sticky ='w')

def on_paste(self):
self.label.configure(image ='')
self.update_idletasks()

试试:
b = bytearray()
h =''self中的c的
.clipboard_get(type ='image / png'):
if c =='':
try:
b.append(int(h,0))
例外,例如e:
print('Exception:{}'。format(e))
h =''
else :
h + = c

,除了tk.TclError如e:
b = None
print('TclError:{}'。format(e))$ b $最终b:
,如果b不是None:
,Image.open(io.BytesIO(b))为img:
print('{}'。format(img))
self.label.image = ImageTk.PhotoImage(img.resize((100,100),Image.LANCZOS))
self.label.configure(image = self.label.image)

使用Python测试:3.5-'TclVersion':8.6'TkVersion':8.6


I have some Python code that edits image files and would like to know how
to add image data to the Operating System clipboard and get it from there.

When searching for a cross-platform solution to replace or get clipboard text in Python,
there were many simple answers to do it (e.g. using the built-in Tkinter module with some code).
However, these methods could only use plain text, not other clipboard data like images.

My version of Python is 3.x on Windows but the answer needs to be cross-platform
(work on different operating systems) and should also support other Python versions like 2.x.
I think it should only use built-in Python modules and the code shouldn't be too complex (or have an explanation of what it does). It can be a Python module because the files can be included in the same folder as portable program code to avoid installing.

There are some other related questions to this one that probably work for images but they only support an individual operating system. The best were Copy image to clipboard in Python3 and Write image to Windows clipboard in python with PIL and win32clipboard?.
The methods described there (for Windows only) appear to use the following steps:

  • Get raw binary data of the image - the method loads an image file with the Python Imaging
    Library (PIL/Pillow) module because this has other processing features used later, in a simple
    and popular standard API. This could be done with a different module instead (e.g. Pygame).
  • Create a file object variable (for in-memory input/output streaming), using the built-in io
    module. For Python 2.x, from cStringIO import StringIO is used but with Python 3, the
    better io.BytesIO binary stream object type is used - the older ones now only allow text.
  • Save the image data, in the BMP (Windows Bitmap/Device Independent Bitmap) file format,
    to the file object variable from the previous step. The method using PIL/Pillow first converts
    this data with .convert("RGB") on the variable containing it.
  • Get the full contents of the file object variable memory buffer as binary data (bytes object),
    slice it from position 14 to remove the 14-byte header of the BMP/DIB file format, then save it
    as a variable. The method says the slicing of this data works on 32 or 64 bit systems but
    needs the Windows clipboard API so doesn't work for a different file format.
  • Close the memory buffer and copy the image data from the previous step to the clipboard.
    The method does this on Windows using the win32clipboard part of an extension module -
    it opens the clipboard for use, clears it, sets its value to the image data variable from the
    previous step (using the BMP/DIB type) then closes the open clipboard.

Also, there's a simple cross-platform clipboard text module called Pyperclip, which is
only a single file for version 1.5.6 and maybe has code that could process image data.

解决方案

Question: How to add/get image data in the OS clipboard using Python?

I show only get:
This example is using the built-in Tkinter module to get image data from CLIPBOARD.
Tested only on Linux, but should be a cross-platform solution.

Note: The first paste of the shown 387x388 GIF, takes 4 seconds.


Core point: You have to use a MIME-Type, to requests a image.

.clipboard_get(type='image/png')

Verfied with, 'GIF', 'PNG' and 'JPEG', as source image data, using application, GIMP and PyCharm. With type='image/png' you allways get image data of type 'PNG' if the source app support this.


Reference:

  • clippboard_get(type=<string>)

    Retrieve data from the clipboard. Type specifies the form in which the data is to be returned and should be an atom name such as STRING or FILE_NAME. Type defaults on modern X11 systems to UTF8_STRING.


Data format:

0x89 0x50 0x4e 0x47 0xd 0xa 0x1a 0xa 0x0 0x0 0x0 0xd 0x49 0x48 0x44

The data is divided into fields separated by white space; each field is converted to its atom value, and the 32-bit atom value is transmitted instead of the atom name.

After removing the white space and casting with int(<field>, 0):

bytearray(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHD...')
<PIL.PngImagePlugin.PngImageFile image mode=P size=387x388 at 0xF555E20C>


Exception: If no selection at all or the source app does not provide 'image/png'.

TclError:CLIPBOARD selection doesn't exist or form "image/png" not defined


import tkinter as tk
from PIL import Image, ImageTk
import io


class App(tk.Tk):
    def __init__(self):
        super().__init__()  # options=(tk.Menu,))
        self.menubar = tk.Menu()
        self.config(menu=self.menubar)
        self.menubar.add_command(label='paste', command=self.on_paste)
        
        self.label = tk.Label(self, text="CLIPBOARD image", font=("David", 18),
                              image='', compound='center')
        self.label.grid(row=0, column=0, sticky='w')

    def on_paste(self):
        self.label.configure(image='')
        self.update_idletasks()
        
        try:
            b = bytearray()
            h = ''
            for c in self.clipboard_get(type='image/png'):
                if c == ' ':
                    try:
                        b.append(int(h, 0))
                    except Exception as e:
                        print('Exception:{}'.format(e))
                    h = ''
                else:
                    h += c

        except tk.TclError as e:
            b = None
            print('TclError:{}'.format(e))
        finally:
            if b is not None:
                with Image.open(io.BytesIO(b)) as img:
                    print('{}'.format(img))
                    self.label.image = ImageTk.PhotoImage(img.resize((100, 100), Image.LANCZOS))
                    self.label.configure(image=self.label.image)

Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6

这篇关于如何使用Python在OS剪贴板中添加/获取图像数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆