Take a screenshot via a Python script on Linux

后端 未结 15 1003
暖寄归人
暖寄归人 2020-11-22 11:50

I want to take a screenshot via a python script and unobtrusively save it.

I\'m only interested in the Linux solution, and should support any X based environment.

相关标签:
15条回答
  • 2020-11-22 12:19

    I have a wrapper project (pyscreenshot) for scrot, imagemagick, pyqt, wx and pygtk. If you have one of them, you can use it. All solutions are included from this discussion.

    Install:

    easy_install pyscreenshot
    

    Example:

    import pyscreenshot as ImageGrab
    
    # fullscreen
    im=ImageGrab.grab()
    im.show()
    
    # part of the screen
    im=ImageGrab.grab(bbox=(10,10,500,500))
    im.show()
    
    # to file
    ImageGrab.grab_to_file('im.png')
    
    0 讨论(0)
  • 2020-11-22 12:20

    bit late but nevermind easy one is

    import autopy
    import time
    time.sleep(2)
    b = autopy.bitmap.capture_screen()
    b.save("C:/Users/mak/Desktop/m.png")
    
    0 讨论(0)
  • 2020-11-22 12:20

    I couldn't take screenshot in Linux with pyscreenshot or scrot because output of pyscreenshot was just a black screen png image file.

    but thank god there was another very easy way for taking screenshot in Linux without installing anything. just put below code in your directory and run with python demo.py

    import os
    os.system("gnome-screenshot --file=this_directory.png")
    

    also there is many available options for gnome-screenshot --help

    Application Options:
      -c, --clipboard                Send the grab directly to the clipboard
      -w, --window                   Grab a window instead of the entire screen
      -a, --area                     Grab an area of the screen instead of the entire screen
      -b, --include-border           Include the window border with the screenshot
      -B, --remove-border            Remove the window border from the screenshot
      -p, --include-pointer          Include the pointer with the screenshot
      -d, --delay=seconds            Take screenshot after specified delay [in seconds]
      -e, --border-effect=effect     Effect to add to the border (shadow, border, vintage or none)
      -i, --interactive              Interactively set options
      -f, --file=filename            Save screenshot directly to this file
      --version                      Print version information and exit
      --display=DISPLAY              X display to use
    
    0 讨论(0)
  • 2020-11-22 12:22

    This one works on X11, and perhaps on Windows too (someone, please check). Needs PyQt4:

    import sys
    from PyQt4.QtGui import QPixmap, QApplication
    app = QApplication(sys.argv)
    QPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png')
    
    0 讨论(0)
  • 2020-11-22 12:24

    Compile all answers in one class. Outputs PIL image.

    #!/usr/bin/env python
    # encoding: utf-8
    """
    screengrab.py
    
    Created by Alex Snet on 2011-10-10.
    Copyright (c) 2011 CodeTeam. All rights reserved.
    """
    
    import sys
    import os
    
    import Image
    
    
    class screengrab:
        def __init__(self):
            try:
                import gtk
            except ImportError:
                pass
            else:
                self.screen = self.getScreenByGtk
    
            try:
                import PyQt4
            except ImportError:
                pass
            else:
                self.screen = self.getScreenByQt
    
            try:
                import wx
            except ImportError:
                pass
            else:
                self.screen = self.getScreenByWx
    
            try:
                import ImageGrab
            except ImportError:
                pass
            else:
                self.screen = self.getScreenByPIL
    
    
        def getScreenByGtk(self):
            import gtk.gdk      
            w = gtk.gdk.get_default_root_window()
            sz = w.get_size()
            pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
            pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
            if pb is None:
                return False
            else:
                width,height = pb.get_width(),pb.get_height()
                return Image.fromstring("RGB",(width,height),pb.get_pixels() )
    
        def getScreenByQt(self):
            from PyQt4.QtGui import QPixmap, QApplication
            from PyQt4.Qt import QBuffer, QIODevice
            import StringIO
            app = QApplication(sys.argv)
            buffer = QBuffer()
            buffer.open(QIODevice.ReadWrite)
            QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
            strio = StringIO.StringIO()
            strio.write(buffer.data())
            buffer.close()
            del app
            strio.seek(0)
            return Image.open(strio)
    
        def getScreenByPIL(self):
            import ImageGrab
            img = ImageGrab.grab()
            return img
    
        def getScreenByWx(self):
            import wx
            wx.App()  # Need to create an App instance before doing anything
            screen = wx.ScreenDC()
            size = screen.GetSize()
            bmp = wx.EmptyBitmap(size[0], size[1])
            mem = wx.MemoryDC(bmp)
            mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
            del mem  # Release bitmap
            #bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
            myWxImage = wx.ImageFromBitmap( myBitmap )
            PilImage = Image.new( 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )
            PilImage.fromstring( myWxImage.GetData() )
            return PilImage
    
    if __name__ == '__main__':
        s = screengrab()
        screen = s.screen()
        screen.show()
    
    0 讨论(0)
  • 2020-11-22 12:25

    You can use this

    import os
    os.system("import -window root screen_shot.png")
    
    0 讨论(0)
提交回复
热议问题