Take a screenshot using Python script on Linux

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

I am only interested in the Linux solution and should support any X-based environment.

+77
python linux screenshot
Sep 16 '08 at 5:44
source share
16 answers

This works without using scrot or ImageMagick.

import gtk.gdk w = gtk.gdk.get_default_root_window() sz = w.get_size() print "The size of the window is %dx %d" % sz 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 != None): pb.save("screenshot.png","png") print "Screenshot saved to screenshot.png." else: print "Unable to get the screenshot." 

Adapted from http://ubuntuforums.org/showpost.php?p=2681009&postcount=5

+64
Apr 23 '09 at 17:27
source share

Compile all the answers in one class. Displays a 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() 
+46
Oct 10 2018-11-11T00:
source share

Just for completeness: Xlib - but it is somewhat slow to capture the entire screen:

 from Xlib import display, X import Image #PIL W,H = 200,200 dsp = display.Display() root = dsp.screen().root raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff) image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX") image.show() 

You can try adding some types to the bottlenecks in PyXlib and then compile them using Cython. This can slightly increase speed.




Edit: We can write the core of a function in C and then use it in Python from ctypes, here is what I hacked together:

 #include <stdio.h> #include <X11/Xh> #include <X11/Xlib.h> //Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c void getScreen(const int, const int, const int, const int, unsigned char *); void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data) { Display *display = XOpenDisplay(NULL); Window root = DefaultRootWindow(display); XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap); unsigned long red_mask = image->red_mask; unsigned long green_mask = image->green_mask; unsigned long blue_mask = image->blue_mask; int x, y; int ii = 0; for (y = 0; y < H; y++) { for (x = 0; x < W; x++) { unsigned long pixel = XGetPixel(image,x,y); unsigned char blue = (pixel & blue_mask); unsigned char green = (pixel & green_mask) >> 8; unsigned char red = (pixel & red_mask) >> 16; data[ii + 2] = blue; data[ii + 1] = green; data[ii + 0] = red; ii += 3; } } XDestroyImage(image); XDestroyWindow(display, root); XCloseDisplay(display); } 

And then the python file:

 import ctypes import os from PIL import Image LibName = 'prtscn.so' AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName grab = ctypes.CDLL(AbsLibPath) def grab_screen(x1,y1,x2,y2): w, h = x2-x1, y2-y1 size = w * h objlength = size * 3 grab.getScreen.argtypes = [] result = (ctypes.c_ubyte*objlength)() grab.getScreen(x1,y1, w, h, result) return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1) if __name__ == '__main__': im = grab_screen(0,0,1440,900) im.show() 
+34
Apr 22 '13 at 6:52
source share

This works on X11, and possibly on Windows too (someone, please check). PyQt4 required:

 import sys from PyQt4.QtGui import QPixmap, QApplication app = QApplication(sys.argv) QPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png') 
+18
Apr 20 '09 at 17:12
source share

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

Installation:

 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') 
+15
Oct 19 '11 at 6:44
source share

Cross platform solution using wxPython :

 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) 
+8
Jun 17 2018-11-11T00:
source share
 import ImageGrab img = ImageGrab.grab() img.save('test.jpg','JPEG') 

this requires a Python image library

+7
Sep 16 '08 at 8:01
source share

A quick search turned out to be gtkShots looks like it can help you, since it is a Python GPLed screenshot program, so it should have what you need in it.

+3
Sep 16 '08 at 7:24
source share

You can use this

 import os os.system("import -window root screen_shot.png") 
+3
Sep 28 '18 at 6:37
source share

There is a python package for Autopy

The bitmap module can display capture (bitmap.capture_screen) This is a multipateform (Windows, Linux, Osx).

+2
May 12 '14 at 12:44
source share

bit late, but indifferently light -

 import autopy import time time.sleep(2) b = autopy.bitmap.capture_screen() b.save("C:/Users/mak/Desktop/m.png") 
+2
May 28 '15 at 10:17
source share

From this thread :

  import os os.system("import -window root temp.png") 
+1
Mar 19 '15 at 3:05
source share

I could not take a screenshot in Linux with pyscreenshot or scrot because the output of pyscreenshot was just a black and white png image file.

but thank god there is another very simple way to take a screenshot in linux without installing anything. just enter below code in your directory and run python demo.py

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

there are also many options available 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 
+1
Aug 08 '17 at 23:57 on
source share

I recently wrote a package that takes a screenshot using the X11 library and returns an image as an array. I actually used some of the suggestions that are mentioned in this thread and improved them. A typical frame rate of 60+ frames per second for 1080p resolution is possible on a modern computer. In fact, on my development machine (which is ~ 3 years old) I managed to get 200 frames per second. here is a link to the project https://github.com/mherkazandjian/fastgrab

+1
Feb 12 '19 at 20:00
source share

This is an old question. I would like to answer it with new tools.

Works with python 3 (should work with python 2, but I have not tested it) and PyQt5.

Minimal working example. Copy it to the python shell and get the result.

 from PyQt5.QtWidgets import QApplication app = QApplication([]) screen = app.primaryScreen() screenshot = screen.grabWindow(QApplication.desktop().winId()) screenshot.save('/tmp/screenshot.png') 
0
Sep 12 '14 at
source share

Try:

 #!/usr/bin/python import gtk.gdk import time import random import socket import fcntl import struct import getpass import os import paramiko while 1: # generate a random time between 120 and 300 sec random_time = random.randrange(20,25) # wait between 120 and 300 seconds (or between 2 and 5 minutes) print "Next picture in: %.2f minutes" % (float(random_time) / 60) time.sleep(random_time) w = gtk.gdk.get_default_root_window() sz = w.get_size() print "The size of the window is %dx %d" % sz 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]) ts = time.asctime( time.localtime(time.time()) ) date = time.strftime("%d-%m-%Y") timer = time.strftime("%I:%M:%S%p") filename = timer filename += ".png" if (pb != None): username = getpass.getuser() #Get username newpath = r'screenshots/'+username+'/'+date #screenshot save path if not os.path.exists(newpath): os.makedirs(newpath) saveas = os.path.join(newpath,filename) print saveas pb.save(saveas,"png") else: print "Unable to get the screenshot." 
-3
Nov 26 '13 at 14:23
source share



All Articles