Is there a faster alternative to GDI GetPixel()?
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.