65.9K
CodeProject is changing. Read more.
Home

FastPixel - A much faster alternative to Bitmap.SetPixel

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.14/5 (22 votes)

Aug 16, 2006

CPOL
viewsIcon

116792

downloadIcon

3013

Ever wanted something faster than SetPixel? Well, you've found it.

Sample Image - screenShot.jpg

Introduction

I have been working on some graphics code lately, and have been quite irritated with SetPixel and its performance overheads. There is an alternative though: lock the bitmap and interact directly with an array of bytes each representing R, G, or B (and sometimes A, depending on whether it's an alpha bitmap or not).

Usage

Dim fp As New FastPixel(image)
fp.Lock()
fp.SetPixel(x, y, Color.Green)
fp.Unlock(True)

What I've learnt

  • Using Bitmap.Width or Bitmap.Height during an intense operation is very slow, because GdipGetImageWidth (or GdipGetImageHeight) is used to retrieve the value, and it isn't cached.
  • Using this class introduces speeds over 20 times faster than using SetPixel, on average.

Conclusion

Use the class!

Sorry about the length of this article, but there isn't much to explain. It's quite basic, and I just wanted to get it out there so people could use it :>