如何在Python中从剪贴板复制图像?

4
def Clip(self):
    subprocess.call('SnippingTool.exe')
    #ctypes.windll.user32.OpenClipboard(0)
    #ClippedScreen=ctypes.windll.user32.GetClipboardData
    #ClippedScreen=PIL.ImageGrab.grab(bbox=(10,10,500,500))
    ClippedScreen = PIL.ImageGrab.grabclipboard()
    self.savescreenshot(ClippedScreen)
  1. ImageGrab.grabclipboard()出现了错误,提示raise IOError("Unsupported BMP bitfields layout")。在网络上看到这是一个已知问题,不知道该如何解决。

  2. 接下来尝试使用ctypes,但出现了错误AttributeError: '_FuncPtr' object has no attribute 'save'

  3. bbox可以工作,但我不知道如何使剪切区域动态化。

全屏截图正常工作。

def Prntscrn(self):
            WholeScreen=ImageGrab.grab()
            self.savescreenshot(WholeScreen)

任何帮助都将是大有裨益的,这个想法是使用剪切工具剪辑屏幕,然后将图像从剪贴板复制到变量中,并使用savescreenshot方法将其保存在文件夹中。求您的协助。
3个回答

4

使用ImageGrab保存剪贴板中的图片

如何实现?

需要在运行环境下安装python==2.7 pillow==2.7.0

from PIL import ImageGrab, Image
im= ImageGrab.grabclipboard()
if isinstance(im, Image.Image):
    im.save('tmp.jpg')

为什么会出现该错误?

IOError: 不支持的BMP位字段布局

在Pillow 2.8.0、2.8.1、2.8.2中可以复现该问题。但在Pillow 2.6.0、2.7.0中无法复现该问题。 https://github.com/python-pillow/Pillow/issues/1293

注意事项

很抱歉通知您,此功能仅适用于Windows操作系统


适用于MacOS的Python 3.6.9和PIL 6.2.1。一个两行OCR程序是python3 clipocr.py tesseract tmp.jpg ocr - Wolfgang Fahl

1
我所知道的唯一方法是使用gtk。示例
window = gtk.screen_get_default().get_root_window()
coordinates = (0, 0) + window.get_size() # (0, 0) is the x and y positions, get_size() is the width and height of the window.
pix = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, *coordinates[2:]) # size of the image
colormap = window.get_colormap()
pix.get_from_drawable(window, colormap, coordinates[0], coordinates[1], 0, 0) # The last four numbers are where in the window we are getting this image and where in the pixbuf we are storing it.  We want the window to be drawn at 0, 0 always, but we want to get the image from wherever we want.  That is decided when we define coordinates.
clipboard = gtk.Clipboard()
clipboard.set_image(pix)

关于pygtk的有用信息,请查看developer.gnome.org


这适用于Windows吗? - Dip Chatterjee
我没有Windows电脑,所以我没有测试过;但是gtk应该可以在Windows上运行。 - zondo

0

好的,我终于找到了解决这个问题的方法。问题存在于Pillow版本2.8.0以来。

根据此链接所述。此外,最后一个可用版本是2.7.0

因为问题出现在BmpImagePlugin.py文件中,所以我下载了这里的Pillow-2.7.0.tar.gz(md5),并将其中的BmpImagePlugin.py替换掉我D:\Python\Lib\site-packages\PIL中找到的那个文件。一切都完美地解决了。

我尝试使用cmd命令提示符安装2.7.0,但一直出现一些批处理文件丢失错误(与Visual Studio相关的问题)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接