Thursday, February 3, 2011

How to Brighten an Image in WPF

Now I'm just getting carried away with playing with image manipulation in WPF. Here's a short post on how to brighten an image using the WriteableBitmap class.

The process is fairly simple, I manipulate each pixel by incrementing each RGB value with the provided level

unsafe static BitmapSource Brighten(BitmapSource image, double level)
{
    const int PIXEL_SIZE = 4;
    int height = image.PixelHeight;
    int width = image.PixelWidth;
 
    var bitmap = new WriteableBitmap(image);            
    bitmap.Lock();
 
    var backBuffer = (byte*)bitmap.BackBuffer.ToPointer();
    for (int y = 0; y < height; y++)
    {
        var row = backBuffer + (y * bitmap.BackBufferStride);
        for (int x = 0; x < width; x++)
            for (int i = 0; i < PIXEL_SIZE; i++)
                row[x * PIXEL_SIZE + i] = (byte)Math.Min(row[x * PIXEL_SIZE + i] + level, 255);
    }
 
    bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
    bitmap.Unlock();
 
    return bitmap;
}


Hope you found this useful

No comments:

Post a Comment