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

How to copy a image from clipboard in Python?

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 方法将其保存在文件夹中。任何帮助都会很棒。

我知道的唯一方法是使用 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

好的。我终于找到了解决这个问题的方法。自版本 2.8.0

以来,Pillow 中就存在该问题

AS per this link. Also as mentioned here the last version in which this worked was 2.7.0

所以问题出在 BmpImagePlugin.py 文件上,我所做的是从 here 下载 Pillow-2.7.0.tar.gz (md5) 并替换 BmpImagePlugin.py 在我的 D:\Python\Lib\site-packages\PIL 中找到与在下载文件中找到的那个。一切都很完美。

我尝试使用 cmd 提示安装 2.7.0,但不断出现一些 bat 文件丢失错误(与 Visual Studio 相关的问题)。

为ImageGrab保存剪贴板

如何!

运行 python==2.7 枕头==2.7.0

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

为什么?

IOError: Unsupported BMP bitfields layout

Reproducible with Pilllow 2.8.0, 2.8.1, 2.8.2. Not reproducible with Pillow 2.6.0, 2.7.0 https://github.com/python-pillow/Pillow/issues/1293

通知

sorry to notice that is was only work on windows