.
GDI+ FAQ
Skip Navigation LinksWelcome : GDI+ FAQ : Adjusting the contrast of an image

Adjusting The Contrast Of An Image.

Image contrast is a function of scale. This is to say that the relative differences between one pixel and the next are increased with greater contrast and decreased with smaller contrast. The easiest way to perform this adjustment with GDI+ is using the ColorMatrix class to scale the pixels.

The ColorMatrix is used in conjunction with the ImageAttributes class to process the pixels of an image as it is drawn so, to get an image with different contrast we just need a method of setting the scale of the red, green and blue elements to the same relative values. This is accomplished with a ColorMatrix that looks like the one shown below.

C 0 0 0 0

0 C 0 0 0

0 0 C 0 0

0 0 0 1 0

0 0 0 0 1

 

In this case the "C" is the contrast scale component. To leave the contrast as it is in the original, the contrast scaling value may be set to 1.0. This creates an identity matrix which will process the image without change. To halve the contrast you can use 0.5 and to double it you would use 2. The setting in matrix position [3,3] is to maintain the alpha component unchanged.

 

Adjusting the contrast in this manner also changes the brightness of an image. Reducing contrast makes the image darker because reducing the scale of the colours moves the RGB values towards zero. Conversely, increasing the scale makes the image brighter because the values are driven towards the maximum of 255. Images that are adjusted for color also often need to be adjusted for brightness.

 

A Bug or a Feature?

 

There is one small problem with this theory and that is the ColorMatrix has a nasty habit of causing arithmetic overflows in the images colour values such that simply scaling will cause an undesirable colourization of the image. Any red, green or blue colour elements having a zero value can overflow to some large value which causes the pixel to take on a totally different colour. To fix this, and it is a blatant fudge, we simply need to shift the colours minutely in one direction or another and the problem goes away. The fudge in the code below offsets the image colours by a measly 0.001, just a tenth of one percent. This means that our final matrix looks like this...

 

C     0     0     0 0

0     C     0     0 0

0     0     C     0 0

0     0     0     1 0

0.001 0.001 0.001 0 1

 

The colour purists may complain but it's better than the alternative.

 

The following listings show an application that enables you to adjust the contrast of an image.

 

Show me code in C#

 

Show me code in VB

 

Return to the GDI+ FAQ

 

Copyright Bob Powell 2004. All rights reserved

Sponsored By
DaraizeTechnologies.com
Bob Powell

Create your badge

Copyright © Bob Powell 2000-2012.  All rights reserved.