Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a faster alternative to GDI GetPixel()?

I'm using GetPixel() from gdi32.dll in a .NET app to sample the colour of a pixel anywhere on the screen. It works ok but it is a major performance bottleneck for me.

Is there a faster way of doing it?

like image 273
stucampbell Avatar asked Nov 21 '10 00:11

stucampbell


2 Answers

Fast access to pixels are possible using LockBits() method of the Bitmap. This will return to you an object containing a pointer to the start of the pixel data and you can use unsafe code to access the memory.

https://web.archive.org/web/20150330113356/http://bobpowell.net/lockingbits.aspx

like image 106
Aliostad Avatar answered Oct 29 '22 17:10

Aliostad


GetPixel is slow for two reasons:

  1. Since you're polling the screen - every call to GetPixel leads to a transaction to the video driver, which in turn takes the pixel data from the video memory.

    In constrast using GetPixel on DIBs is very much faster.

  2. Anyway GetPixel does several things, including coordinates clipping/transformations and etc.

So that if you're using to query many pixel values at once - you should try to arrange this in a single transaction to GDI / video driver.

Using GDI you should create a DIB of the adequate size (see CreateDIBSection). After creation you'll be given a direct pointer to the image bits data. Then copy the image part onto your DIB (see BitBlt). Also don't forget to call GdiFlush before you actually check the contents of the DIB (since video drivers may do asynchronous drawing).

Using GD+ you may actually do the same, with a bit simpler syntax.

like image 42
valdo Avatar answered Oct 29 '22 17:10

valdo