Python windows 7 screenshot without PIL

2019-01-22 00:27发布

问题:

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?

回答1:

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')


回答2:

32- or 64-bit Windows is irrelevant here; it is the 'bit-ness' of Python and its modules that matter. If you are running 32-bit-compiled Python, 32-bit-compiled PIL will work just fine on 64-bit Windows.

On the other hand, if you are running 64-bit-compiled Python, you need to find or custom-compile a 64-bit-compiled version of PIL to match.

Edit:

You can download a 64-bit-compiled version of PIL from http://www.lfd.uci.edu/~gohlke/pythonlibs/ - specifically, you want PIL-1.1.7.win-amd64-py2.7.‌exe



回答3:

I got the same problem on PIL or pyscreenshot, here's how I solved it.

Right-click on python.exe, Properties, Compatibility tab, check 'Disable display scaling on high DPI settings'. Repeat for pythonw.exe.