Đây là nguồn màn hình lấy của PIL, Nó không chấp nhận bất kỳ tham số nào và nó lấy toàn bộ màn hình và chuyển đổi thành bitmap. Cách tiếp cận C
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;
}
Vì vậy, khi tôi chỉ cần đi một chút sâu, tìm thấy là tốt
http://msdn.microsoft.com/en-us/library/dd144909(VS.85).aspx
Và Python có ctypes, Vì vậy, đây là cách tiếp cận của tôi sử dụng 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
Bạn có thể viết trình bao bọc cho hàm GetPixel như thế này
from ctypes import windll
dc= windll.user32.GetDC(0)
def getpixel(x,y):
return windll.gdi32.GetPixel(dc,x,y)
Sau đó, bạn có thể sử dụng như getpixel(0,0)
, getpixel(100,0)
, vv ...
PS: Mine là Windows 2000, vì vậy tôi đặt winnt
trong đường dẫn, bạn có thể cần phải thay đổi nó để windows
hoặc bạn chould loại bỏ hoàn toàn đường dẫn, chỉ cần sử dụng user32.dll
và gdi32.dll
cũng sẽ hoạt động.
Cảm ơn một bó. Màn hình tăng tốc này đọc NOTICEABLY. Tôi có thể đọc nhanh như tôi muốn bây giờ với hầu như không có sự chậm lại. ;) – ThantiK
Tôi đã thử cú pháp trên cho ctypes và không thể làm cho nó hoạt động với LoadLibrary. Mã hàm của hàm bao bọc là chính xác những gì tôi đang tìm kiếm. – Octipi
Tôi không thể tin rằng điều này thực sự hoạt động với thời gian ít nhất 30 lần trong giây. Tôi đã thử GetPixel và mất rất nhiều thời gian. –