views:

53

answers:

1

Do you think the following one is best for adjusting Contrast level? In fact, I would like to get the same/close perfromance for adjusting contrast as found in Photoshop.

public static Bitmap AdjustContrast(Bitmap Image, float Value)
{
    Value = (100.0f + Value) / 100.0f;
    Value *= Value;
    System.Drawing.Bitmap NewBitmap = Image;

    for (int x = 0; x < NewBitmap.Width; ++x)
    {
        for (int y = 0; y < NewBitmap.Height; ++y)
        {
            Color Pixel = NewBitmap.GetPixel(x, y);
            float Red = Pixel.R / 255.0f;
            float Green = Pixel.G / 255.0f;
            float Blue = Pixel.B / 255.0f;
            Red = (((Red - 0.5f) * Value) + 0.5f) * 255.0f;
            Green = (((Green - 0.5f) * Value) + 0.5f) * 255.0f;
            Blue = (((Blue - 0.5f) * Value) + 0.5f) * 255.0f;
            NewBitmap.SetPixel(x, y, Color.FromArgb(Clamp((int)Red, 255, 0), Clamp((int)Green, 255, 0), Clamp((int)Blue, 255, 0)));
        }
    }

    return NewBitmap;
}

public static T Clamp<T>(T Value, T Max, T Min)
     where T : System.IComparable<T>
{
    if (Value.CompareTo(Max) > 0)
        return Max;
    if (Value.CompareTo(Min) < 0)
        return Min;
    return Value;
}

The above code is not mine and I forgot the source of the code.

A: 

Basically, no. Get and Set pixel are really slow. Try something along this lines of this. It locks the Bitmap's pixels in memory and then directly manipulates that area of memory with a contrast algorithm. It does require unsafe code but if you want any sort of performance out of your solution, that's the way you have to go.

Alternatively, you can use built in matrix manipulations to do basically the same thing. I don't particularly like using them as sometimes it's hard to get the perfect effect. But they might be the easiest thing in your case. Link.

colithium
Thank you so much. Have you ever used these codes (as per link) in any project? Using Colormatrix I did not get good result for adjusting contrast earlier.
Hoque
I actually wrote the code referenced in the first link (many years ago, it's still applicable though). As I said I don't typically rely on the Color Matrix class but it should work. Did you read the accompanying article for the second link? I've never had a problem with that site's advice.
colithium