How to Darken an Image in C#

Thumbnail image of Jason Bauer
Jason Bauer
December 29, 2015 (Last Updated: ) | Reading Time: 1 minutes

In order to darken an image in C# you need to look at each pixel one at a time and decrease it's red, green, and blue values.

Steps To Darken an Image in C#

There are a few ways to do this.

Source Code to Darken an Image in C#

Here's the easy way.

// this code relies on the LockedBitmap class
// darkenAmount should be a value between 0 and 1
private
static void LightenImage(Bitmap bmp, double lightenAmount)
{
    var lockedBitmap = new LockBitmap(bmp);
    lockedBitmap.LockBits();

    for (int y = 0; y < lockedBitmap.Height; y++)
    {
        for (int x = 0; x < lockedBitmap.Width; x++)
        {
            var oldColor = lockedBitmap.GetPixel(x, y);
            var newColor = DarkenColor(oldColor, lightenAmount);
            lockedBitmap.SetPixel(x, y, newColor);
        }
    }
    lockedBitmap.UnlockBits();
}

public
static Color DarkenColor(Color inColor, double lightenAmount)
{
    return Color.FromArgb(
        inColor.A,
        (int)Math.Max(0, inColor.R - 255 * lightenAmount),
        (int)Math.Max(0, inColor.G - 255 * lightenAmount),
        (int)Math.Max(0, inColor.B - 255 * lightenAmount));
}

The Results of Darkening an Image in C#

Here is a test image.

thumbnail
thumbnail

And here are the results of setting darkenAmount to 0.5.

thumbnail
thumbnail

How it Works

This block of code iterates over the images width and height looking at each pixel. For each pixel it calls the function DarkenColor. DarkenColor calculates the amount of "darkenning" to apply for each of the 3 RGB elements and returns a new Color object.

The LockedBits Class

You need to have the LockedBits class in your project in order to use this code. You can learn about it in our How to Load an Image in C# guide.

Other C# Image Processing Guides

You might be interested in some of our other C# Image Processing Guides.

Leave a reply

Thank you! Your comment has been successfully submitted. It will be approved as soon as possible.

More from Efundies