Take a screenshot via a Python script on Linux

后端 未结 15 1248
暖寄归人
暖寄归人 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:27

    for ubuntu this work for me, you can take a screenshot of select window with this:

    import gi
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gdk
    from gi.repository import GdkPixbuf
    import numpy as np
    from Xlib.display import Display
    
    #define the window name
    window_name = 'Spotify'
    
    #define xid of your select 'window'
    def locate_window(stack,window):
        disp = Display()
        NET_WM_NAME = disp.intern_atom('_NET_WM_NAME')
        WM_NAME = disp.intern_atom('WM_NAME') 
        name= []
        for i, w in enumerate(stack):
            win_id =w.get_xid()
            window_obj = disp.create_resource_object('window', win_id)
            for atom in (NET_WM_NAME, WM_NAME):
                window_name=window_obj.get_full_property(atom, 0)
                name.append(window_name.value)
        for l in range(len(stack)):
            if(name[2*l]==window):
                return stack[l]
    
    window = Gdk.get_default_root_window()
    screen = window.get_screen()
    stack = screen.get_window_stack()
    myselectwindow = locate_window(stack,window_name)
    img_pixbuf = Gdk.pixbuf_get_from_window(myselectwindow,*myselectwindow.get_geometry()) 
    

    to transform pixbuf into array

    def pixbuf_to_array(p):
        w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())
        assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB
        assert p.get_bits_per_sample() == 8
        if  p.get_has_alpha():
            assert c == 4
        else:
            assert c == 3
        assert r >= w * c
        a=np.frombuffer(p.get_pixels(),dtype=np.uint8)
        if a.shape[0] == w*c*h:
            return a.reshape( (h, w, c) )
        else:
            b=np.zeros((h,w*c),'uint8')
            for j in range(h):
                b[j,:]=a[r*j:r*j+w*c]
            return b.reshape( (h, w, c) )
    
    beauty_print = pixbuf_to_array(img_pixbuf)
    

提交回复
热议问题