I have a program that reads the grayscale (0 - 255) value of a pixel and changes it to an RGB color (formula see code).
Here is my code:
Bitmap img = new Bitmap(@"somepath");
Bitmap new_img = new Bitmap(img.Width, img.Height);
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
Color pixel = img.GetPixel(i, j);
Color my = new Color();
int R_new = 0;
if (pixel.R > 126)
{
R_new = (pixel.R -127) / 128 * 255;
}
int B_new = 0;
if (pixel.B < 128) {
B_new = (1 - pixel.R / 127) * 255;
}
int G_new = 0;
if (pixel.G < 128) {
G_new = pixel.R/127 * 255;
}
my = Color.FromArgb(R_new, G_new, B_new);
new_img.SetPixel(i, j, my);
}
}
new_img.Save(@"C:somepath");
In the following picture you can see the green-value of the old pixel is 6 and of the new pixel it is set with 255, which is wrong. According to the formula it should be set at 12.
Here is my question: Why is the value of the pixel set wrong?
You have two problems.
#1: You're passing the blue value in place of the green value. Check the expected order of arguments :
Color.FromArgb(int red, , int blue)
#2: B_new
is 255
due to how integer division is handled:
For the operands of integer types, the result of the
/
operator is of an integer type and equals the quotient of the two operands rounded towards zero:
(1 - 6 / 127) * 255 // becomes 255
So, 6 / 127
equals 0.047244094488189
but it's rounded down to zero... making your formula:
(1 - 0) * 255 // becomes 255
Make at least one of your division terms a floating point type and you'll get a decimal value:
(1 - pixel.R / ) * 255 // becomes 242.9527559055118
... which you'll then have to convert to an int
to conform to the method signature of Color.FromArgb(int, int, int)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.