Skip to content

Instantly share code, notes, and snippets.

@globby
Created March 8, 2014 04:06
Show Gist options
  • Save globby/9425184 to your computer and use it in GitHub Desktop.
Save globby/9425184 to your computer and use it in GitHub Desktop.
A simple(ish) screencap program with ctypes and PIL
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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment