這是PIL的grabscreen源碼,它不接受任何參數,並且抓取整個屏幕並將其轉換爲位圖。
PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
{
int width, height;
HBITMAP bitmap;
BITMAPCOREHEADER core;
HDC screen, screen_copy;
PyObject* buffer;
/* step 1: create a memory DC large enough to hold the
entire screen */
screen = CreateDC(";DISPLAY", NULL, NULL, NULL);
screen_copy = CreateCompatibleDC(screen);
width = GetDeviceCaps(screen, HORZRES);
height = GetDeviceCaps(screen, VERTRES);
bitmap = CreateCompatibleBitmap(screen, width, height);
if (!bitmap)
goto error;
if (!SelectObject(screen_copy, bitmap))
goto error;
/* step 2: copy bits into memory DC bitmap */
if (!BitBlt(screen_copy, 0, 0, width, height, screen, 0, 0, SRCCOPY))
goto error;
/* step 3: extract bits from bitmap */
buffer = PyString_FromStringAndSize(NULL, height * ((width*3 + 3) & -4));
if (!buffer)
return NULL;
core.bcSize = sizeof(core);
core.bcWidth = width;
core.bcHeight = height;
core.bcPlanes = 1;
core.bcBitCount = 24;
if (!GetDIBits(screen_copy, bitmap, 0, height, PyString_AS_STRING(buffer),
(BITMAPINFO*) &core, DIB_RGB_COLORS))
goto error;
DeleteObject(bitmap);
DeleteDC(screen_copy);
DeleteDC(screen);
return Py_BuildValue("(ii)N", width, height, buffer);
error:
PyErr_SetString(PyExc_IOError, "screen grab failed");
DeleteDC(screen_copy);
DeleteDC(screen);
return NULL;
}
所以,當我剛去略深,測得C的做法是好的
http://msdn.microsoft.com/en-us/library/dd144909(VS.85).aspx
和Python有ctypes的,所以這裏是一個使用ctypes的
>>> from ctypes import *
>>> user= windll.LoadLibrary("c:\\winnt\\system32\\user32.dll") #I am in windows 2000, may be yours will be windows
>>> h = user.GetDC(0)
>>> gdi= windll.LoadLibrary("c:\\winnt\\system32\\gdi32.dll")
>>> gdi.GetPixel(h,1023,767)
16777215 #I believe its white color of RGB or BGR value, #FFFFFF (according to msdn it should be RGB)
>>> gdi.GetPixel(h,1024,767)
-1 #because my screen is only 1024x768
我的方法你可以寫一個函數GetPixel的包裝,像這樣
from ctypes import windll
dc= windll.user32.GetDC(0)
def getpixel(x,y):
return windll.gdi32.GetPixel(dc,x,y)
然後你可以使用像getpixel(0,0)
,getpixel(100,0)
,等...
PS:我的是Windows 2000的,所以我把winnt
的路徑,則可能需要將其更改爲windows
,或者你chould完全刪除路徑,只需使用user32.dll
和gdi32.dll
即可。在S.Mark的解決方案
感謝一大堆。這加快了屏幕閱讀NOTICEABLY。我現在可以像現在想的那樣快速閱讀,而且幾乎沒有減速。 ;) – ThantiK 2010-01-13 22:14:52
我嘗試了ctypes的上述語法,無法讓它與LoadLibrary一起工作。包裝函數代碼正是我所期待的。 – Octipi 2013-07-30 09:08:46
我不能相信這個實際上至少在第二次的時間裏有30次。我試過GetPixel,花了很多時間。 – 2016-01-19 08:26:26