Applying contrast makes the image black

Here’s my contrast script:

public void ApplyContrast(string contrast)
    {
            double contrastD = Convert.ToDouble(contrast);
			
            Texture2D bitmapImage = new Texture2D(imgTexture.width, imgTexture.height);

            if (contrastD < -100) contrastD = -100;
            if (contrastD > 100) contrastD = 100;
            contrastD = (100.0 + contrastD) / 100.0;
            contrastD *= contrastD;
            Color color;
            for (int i = 0; i < bitmapImage.width; i++)
            {
                for (int j = 0; j < bitmapImage.height; j++)
                {
                    color = (imgTexture as Texture2D).GetPixel(i, j);

                    //Alpha 
                    double pA = color.a / 255.0;

                    //Red 
                    double pR = color.r / 255.0;
                    pR -= 0.5;
                    pR *= contrastD;
                    pR += 0.5;
                    pR *= 255;
                    if (pR < 0) pR = 0;
                    if (pR > 255) pR = 255;

                    //Green
                    double pG = color.g / 255.0;
                    pG -= 0.5;
                    pG *= contrastD;
                    pG += 0.5;
                    pG *= 255;
                    if (pG < 0) pG = 0;
                    if (pG > 255) pG = 255;

                    //Blue
                    double pB = color.b / 255.0;
                    pB -= 0.5;
                    pB *= contrastD;
                    pB += 0.5;
                    pB *= 255;
                    if (pB < 0) pB = 0;
                    if (pB > 255) pB = 255;

                    bitmapImage.SetPixel(i, j, new Color((float)pR,(float)pG,(float)pB,(float)pA));
                }
            }

            bitmapImage.Apply();

            Image.renderer.material.mainTexture = bitmapImage as Texture;
    }

I noticed if there is no contrast on the image, the image is loaded correctly but as soon as I apply some contrast starting from 1 to some value, the image turns black. What’s wrong with the contrast script above?

RGB values in Color is between 0 and 1.
Your code

double pR = color.r / 255.0;
                     pR -= 0.5;
                     pR *= contrastD;
                     pR += 0.5;
                     pR *= 255;

makes it go below 0.

If color.r value is at its highest, color.r == 1.
Even at with this value, 1/255 - 0.5 will yield negative values that following code cannot set back to positive values.

Just dont divide by 255 and you will have a not-black texture.