I'm working on a program that works with images. I'm having trouble on a function that adjusts contrast and brightness. I need to calculate a value for each RGB component based on what input I recieve from the user. The problem is, I need to make sure the final value after said calculation isn't greater than 255 or less than 0. So it can fit inside a byte.
temp = c * dataPtr[0] + b; //variable temp is of type double.
if (temp > 255)
{
temp = 255;
}
else if (temp < 0)
{
temp = 0.0;
}
dataPtr[0] = (byte)(Math.Round(temp));
I'm repeating this for every RGB component of every pixel, so the ifs are getting executed a million times, most of the times needlessly.
I thought about just casting a double back to byte but it just reads the first byte of the double and doesn't max out the value if it's greater than what a byte can handle. Is there any obvious way to optmize this this range-check that I'm just missing? Thank you.
No. if
is the "gold standard" way of comparing values. If you need to make sure the the value is in a range if
is the way to do it. If you must have an alternative: use an existing type that can only handle values 0-255, but then "overflow" behavior is "less defined". If you make your own type it probably uses if
inside it anyway.
Your reasons "lots of needless ifs" is nothing to worry about.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments