【发布时间】:2015-05-19 23:02:50
【问题描述】:
所以我正在寻找一种在 C 代码中读取屏幕像素颜色的方法。
我已经在 C 中找到了 *nix 的实现(它使用 X11/Xlib 库,据我所知,它仅适用于 *nix 系统),我在 linux 机器上尝试了代码,它运行得非常快(它读取 8K 像素大约 1 秒)。
这是我找到并分叉的 C 代码:
#include <X11/Xlib.h>
void get_pixel_color (Display *d, int x, int y, XColor *color)
{
XImage *image;
image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
color->pixel = XGetPixel (image, 0, 0);
XFree (image);
XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), color);
}
// Your code
XColor c;
get_pixel_color (display, 30, 40, &c);
printf ("%d %d %d\n", c.red, c.green, c.blue);
我也在寻找适用于 Windows 的等效解决方案。
我遇到了这段代码(我已将有关读取屏幕像素的代码放在“for”循环中):
FARPROC pGetPixel;
HINSTANCE _hGDI = LoadLibrary("gdi32.dll");
if(_hGDI)
{
pGetPixel = GetProcAddress(_hGDI, "GetPixel");
HDC _hdc = GetDC(NULL);
if(_hdc)
{
int i;
int _red;
int _green;
int _blue;
COLORREF _color;
ReleaseDC(NULL, _hdc);
for (i=0;i<8000;i++)
{
_color = (*pGetPixel) (_hdc, 30 ,40);
_red = GetRValue(_color);
_green = GetGValue(_color);
_blue = GetBValue(_color);
}
ReleaseDC(NULL, _hdc);
printf("Red: %d, Green: %d, Blue: %d", _red, _green, _blue);
}
FreeLibrary(_hGDI);
(使用 gdi32.dll 和 windows.h...)
并且代码的“for”部分(我们读取 8K 像素)的运行速度比 C 中的解决方案慢很多。
与 X11/Xlib.h 库 1 秒相比,完成需要 15 秒!
那么,我怎样才能让它变得更好呢?还是有其他更好更快的实现来在 Windows 机器中使用 C 代码读取像素颜色?
先谢谢了!
【问题讨论】:
-
嗯,32KB/秒的带宽并不值得吹嘘。 Windows 要求程序员成为更聪明的读者,Petzold 的书很好地解释了 BitBlt()。
-
您要在这里读取多少像素?只有 1 个,还是要检查一大堆?如果是一大堆,getPixel 可能不是这样做的方法,而是一次将整个屏幕捕获到纹理的方法。
-
是的,我正在尝试阅读一堆...正如我所展示的,*nix 解决方案可以在 1 秒内读取很多像素,而 Windows 解决方案非常慢...任何建议、其他解决方案或资源?我已经在 Windows 中寻找更好的解决方案一段时间了,但我找不到。
-
@HansPassaant - 你能详细说明你的答案吗?你什么意思?它是什么 BitBlt()?如何有效快速地读取屏幕像素?提前谢谢