我正在构建一个项目来获取某些屏幕像素的颜色。该项目已经有效,但我想知道是否有更好更快的方法。这是我正在使用的代码的一部分: 在这里,我想得到某些像素的颜色从像素(265,400)开始,水平移动10步,垂直移动9步,两步之间的差异为40像素。
myBitmap = Win32APICall.GetDesktop();
int DX = 0 ; int DY=0; int index = 1;
MyPoint[,] MyPoint_Array = new MyPoint[10,9]
for(int y = 400;y<750;y+=40)
{
for(int x=266;x<650;x+=40)
{
Color MyColor = myBitmap.GetPixel(x,y);
MyPoint M = new MyPoint(index,MyColor.ToArgb());
MyPoint_Array[DX, DY] = M;
index++;
if (DX < 9)
{ DX++; }
else
{ DX = 0; }
}
if (DY < 8)
{ DY++; }
else
{ DY = 0; }
}
这是类WIN32APICall
的GetDesktop()函数class Win32APICall
{
[DllImport("gdi32.dll", EntryPoint = "DeleteDC")]
public static extern IntPtr DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
public static extern IntPtr DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll", EntryPoint = "BitBlt")]
public static extern bool BitBlt(IntPtr hdcDest, int nXDest,
int nYDest, int nWidth, int nHeight, IntPtr hdcSrc,
int nXSrc, int nYSrc, int dwRop);
[DllImport("gdi32.dll", EntryPoint = "CreateCompatibleBitmap")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc,
int nWidth, int nHeight);
[DllImport("gdi32.dll", EntryPoint = "CreateCompatibleDC")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll", EntryPoint = "SelectObject")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobjBmp);
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll", EntryPoint = "GetDC")]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
public static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll", EntryPoint = "ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
public static Bitmap GetDesktop()
{
int screenX;
int screenY;
IntPtr hBmp;
IntPtr hdcScreen = GetDC(GetDesktopWindow());
IntPtr hdcCompatible = CreateCompatibleDC(hdcScreen);
screenX = GetSystemMetrics(0);
screenY = GetSystemMetrics(1);
hBmp = CreateCompatibleBitmap(hdcScreen, screenX, screenY);
if (hBmp != IntPtr.Zero)
{
IntPtr hOldBmp = (IntPtr)SelectObject(hdcCompatible, hBmp);
BitBlt(hdcCompatible, 0, 0, screenX, screenY, hdcScreen, 0, 0, 13369376);
SelectObject(hdcCompatible, hOldBmp);
DeleteDC(hdcCompatible);
ReleaseDC(GetDesktopWindow(), hdcScreen);
Bitmap bmp = System.Drawing.Image.FromHbitmap(hBmp);
DeleteObject(hBmp);
GC.Collect();
return bmp;
}
return null;
}
}
答案 0 :(得分:0)
从片段中不清楚,但如果您对整个桌面不感兴趣,只想要一小部分,那么请考虑使用Graphics.CopyFromScreen()。不要忘记移动循环,使它们从0(零)开始:
Point upperLeftSouce = new Point(266, 400);
Size blockRegionSize = new Size(385, 351);
Bitmap bmp = new Bitmap(blockRegionSize.Width, blockRegionSize.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(upperLeftSouce, new Point(0, 0), bmp.Size);
}
for (int y = 0; y < bmp.Height; y += 40)
{
for (int x = 0; x < bmp.Width; x += 40)
{
// ... code ..
}
}