scythargon
scythargon

Reputation: 3491

Usage of X displays: make screenshot from window without showing it

My goal is to make screenshot from window without displaying it.

Code: All the Xvfb-things works with QT (example), but seems like I do not fully understand how to use it with GTK.

import gtk,webkit,gobject,sys,os,time
web=webkit.WebView()
url = 'http://google.com/'
web.open(url)
win=gtk.Window()
win.add(web)

silence_xvfb=True
display='1'
screen='0'
xvfb_timeout=3
pidfile = '/tmp/.X%s-lock' % display
redirect = '> /dev/null 2>&1'
if not silence_xvfb:
    redirect = ''
cmd = ' '.join(['Xvfb', ':'+display, '-screen', screen, '1600x1200x24', redirect])
os.system(cmd+' &')

start = time.time()
while(True):
    diff = time.time() - start
    if(diff > xvfb_timeout):
        raise SystemError("Timed-Out waiting for Xvfb to start - {0} sec".format(xvfb_timeout))
    if(os.path.isfile(pidfile)):
        break
    else:
        time.sleep(0.05)

os.putenv('DISPLAY', ':%s' % display)

def drawWindow(win):
    width, height = win.get_size()
    pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)

    screenshot = pixbuf.get_from_drawable(win.window, win.get_colormap(), 
                                          0, 0, 0, 0, width, height)

    screenshot.save('screenshot.png', 'png')
    print 'screenshot saved'

win.show_all()
gobject.timeout_add(5000, drawWindow, win)
gtk.main()

Upvotes: 1

Views: 358

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328614

All X11-based code (Qt, KDE, gtk, wxWindows, ...) uses the DISPLAY variable to define which display to use. See the docs for details.

You problem is that the variable is examined once per process at the time of the first X11 call (more or less).

So in your case, you create a window and then you try to set the DISPLAY variable. X11 can't move existing windows from one instance to another.

What you need to do is split the code above into two processes. One starts Xvfb and sets the DISPLAY variable and the other renders the UI.

Upvotes: 2

Related Questions