Search code examples
pythonimagewindows-7screenshot

Python windows 7 screenshot without PIL


I want to take a screenshot using python.

I have tried using PIL, but since I am using 64bit windows and python PIL does not work (I could only find 32bit PIL versions). I am using python 2.7.1 by the way.

I want to take a screenshot, it doesn't really matter how, as long as it can take more than 1 per second in speed. Preferably it should also be able to crop the area it takes a screenshot of, but that's not of the utmost importance.

The main problem seems to be I'm running on 64bit and a lot of things seem incompatible with that. I don't really want to move back to 32bit though if at all possible. Are there any programs or modules that can do this?


Solution

  • Get PIL for win-amd64-py2.7 at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil.

    from PIL import ImageGrab
    im = ImageGrab.grab()
    im.save('screenshot.png')
    

    Update: use pywin32 (http://sourceforge.net/projects/pywin32/) instead of PIL to take screenshots of multiple virtual screens:

    import win32gui, win32ui, win32con, win32api
    hwin = win32gui.GetDesktopWindow()
    width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
    left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
    bmp.SaveBitmapFile(memdc, 'screenshot.bmp')