posted on November 15, 2011 19:54
I recently stumbled upon a question on Stackoverflow which asked if there was a WPF equivalent of the GDI code ImageAttributes.SetColorMatrix to set the alpha channel of a bitmap in memory.
Well, the short answer is no, there isn't, however there is an excellent open source library which allows direct bitmap manipulations in WPF which could be modified do the above functionality. This is the WriteableBitmapEx library.
This library doesn't have a function per-se to manipulate the Alpha channel, however the short example attached does. The function UpdateOpacity below shows where the work is done. UpdateOpacity gets a pointer to the bitmap and iterate over the pixels (size = stride * height) in steps of 4, starting at index 3. This assumes the Pixel Format is BGRA (hence alpha starts at index 3) and there are 32 bits per pixel. In the attached project, the new alpha value is set by a slider in real-time to demonstrate that this method is fast and reliable in a WPF application.
private void UpdateOpacity(WriteableBitmap bmp, byte alpha)
if (bmp == null)
int w = bmp.PixelWidth;
int h = bmp.PixelHeight;
int stride = bmp.BackBufferStride;
int size = stride * h;
var pixels = (byte*)bmp.BackBuffer;
// Assumbing BGRA format, Alpha component starts at
// index 3 and in steps of 4 until Stride*Height
for (int i = 3; i < size; i+=4)
pixels[i] = alpha;
bmp.AddDirtyRect(new Int32Rect(0, 0, w, h));
Here's the project download: BitmapAlphaChannel.zip