I needed to capture my screen very quickly from python, and needed to save these images into a Python Image Library (PIL) Image. I wrote a small python class to do the work, keeping as little processing as possible in the screenshot.take() function.

import Image, gtk
class screenshot:
    def __init__(self):
        self.img_width = gtk.gdk.screen_width()
        self.img_height = gtk.gdk.screen_height()

        self.screengrab = gtk.gdk.Pixbuf(
            gtk.gdk.COLORSPACE_RGB,
            False,
            8,
            self.img_width,
            self.img_height)

    def take(self):
        self.screengrab.get_from_drawable(
            gtk.gdk.get_default_root_window(),
            gtk.gdk.colormap_get_system(),
            0, 0, 0, 0,
            self.img_width,
            self.img_height)

        final_screengrab = Image.frombuffer(
          "RGB",
          (self.img_width, self.img_height),
          self.screengrab.get_pixels(),
          "raw",
          "RGB",
          self.screengrab.get_rowstride(),
          1)
        return final_screengrab

if __name__ == '__main__':
    import time
    screenshot = screenshot()
    while True:
        ti = time.time()
        im = screenshot.take()
        tii = time.time()
        print tii-ti
Advertisements