Skip to content

Instantly share code, notes, and snippets.

@globby
Created March 8, 2014 04:06

Revisions

  1. globby created this gist Mar 8, 2014.
    31 changes: 31 additions & 0 deletions Screencap.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    from ctypes import *
    from struct import calcsize, pack
    from PIL import Image

    CreateDC = windll.gdi32.CreateDCA
    CreateCompatibleDC = windll.gdi32.CreateCompatibleDC
    GetDeviceCaps = windll.gdi32.GetDeviceCaps
    CreateCompatibleBitmap = windll.gdi32.CreateCompatibleBitmap
    BitBlt = windll.gdi32.BitBlt
    SelectObject = windll.gdi32.SelectObject
    DeleteDC = windll.gdi32.DeleteDC

    NULL = c_int(0)
    HORZRES = c_int(8)
    VERTRES = c_int(10)
    SRCCOPY = c_uint(0x00CC0020)

    screen = CreateDC(c_char_p("DISPLAY"),NULL,NULL,NULL)
    memory = CreateCompatibleDC(screen)
    x = GetDeviceCaps(screen,HORZRES)
    y = GetDeviceCaps(screen,VERTRES)
    bmp = CreateCompatibleBitmap(screen,x,y)
    old_bmp = SelectObject(memory,bmp)
    BitBlt(memory,0,0,x,y,screen,0,0,SRCCOPY)
    screen = SelectObject(memory,old_bmp)
    bmp_header = pack('LHHHH', calcsize('LHHHH'), x, y, 1, 24)
    c_bmp_header = c_buffer(bmp_header)
    c_bits = c_buffer(' ' * (y * ((x * 3 + 3) & -4)))
    got_bits = windll.gdi32.GetDIBits(memory,bmp,0,y,c_bits,c_bmp_header,0)
    im = Image.frombuffer('RGB', (x,y), c_bits,'raw','BGR',(x * 3 + 3) & -4, -1)
    im.save('screencap.jpg')