I want to change the brightness of the image I uploaded in my unity scene. Here’s my current script:
public void AdjustBrightness(string brightness)
{
int brightnessInt = Convert.ToInt32(brightness);
int mappedBrightness = (51 * brightnessInt) / 10 - 255;
//Make an empty Texture the same same as the original
Texture2D bitmapImage = new Texture2D(imgTexture.width, imgTexture.height);
if (mappedBrightness < -255) mappedBrightness = -255;
if (mappedBrightness > 255) mappedBrightness = 255;
Color color;
for (int i = 0; i < bitmapImage.width; i++)
{
for (int j = 0; j < bitmapImage.height; j++)
{
color = bitmapImage.GetPixel(i, j);
int cR = (int)color.r + mappedBrightness;
int cG = (int)color.g + mappedBrightness;
int cB = (int)color.b + mappedBrightness;
if (cR < 0) cR = 0;
if (cR > 255) cR = 255;
if (cG < 0) cG = 0;
if (cG > 255) cG = 255;
if (cB < 0) cB = 0;
if (cB > 255) cB = 255;
bitmapImage.SetPixel(i, j,
new Color((float)cR, (float)cG, (float)cB));
}
}
//Apply all SetPixel changes
bitmapImage.Apply();
//Connect texture to material of GameObject this script is attached to
Image.renderer.material.mainTexture = bitmapImage as Texture;
}
For some reason, this script completely changes my image to black. Then if I increase my values to a certain point, the image turns fully white.
Am I calculating brightness correctly here?
Btw, in the beginning I am mapping the brightness value from my current input range of values between 0% to 100% to -255 to 255 to use this script. Is this fine? That is, there is an input field to enter a brightness value of 0 to 100 and to use this formula, I have to map the value of 50% to what 50% means on the scale/range of -255 to 255 right?