tags:

views:

206

answers:

2

What is the best way to set the RGB components of every pixel in a System.Drawing.Bitmap to a single, solid color? If possible, I'd like to avoid manually looping through each pixel to do this.

Note: I want to keep the same alpha component from the original bitmap. I only want to change the RGB values.

I looked into using a ColorMatrix or ColorMap, but I couldn't find any way to set all pixels to a specific given color with either approach.

+3  A: 

The best (in terms of perf, at least) option is to use Bitmap.LockBits, and loop through the pixel data in the scan line, setting the RGB values.

Since you don't want to change the Alpha, you are going to have to loop through each pixel - there is no single memory assignment that will preserve alpha and replace RGB, since they're interleaved together.

Reed Copsey
+1. Thanks Reed, I'll probably use that for some other stuff I'm doing.
Charles
+4  A: 

Yes, use a ColorMatrix. It ought to look like this:

  0  0  0  0  0
  0  0  0  0  0
  0  0  0  0  0 
  0  0  0  1  0 
  R  G  B  0  1

Where R, G and B are the scaled color values of the replacement color (divide by 255.0f)

Hans Passant
Charles
The zeros in the diagonal produce black, the bottom numbers get added.
Hans Passant
Ah-ha. I wasn't thinking it all through. I bet that should work perfectly. I'll check and be right back with you.
Charles
Excellent! Thanks a bunch, nobugz.
Charles