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?
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
GetPixel
is slow for two reasons:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With