[英]Changing the color of pixles of an Image in c#
I am trying to replace black pixels with red in an image.我正在尝试用图像中的红色替换黑色像素。 Here is my image My_Image这是我的图片My_Image
Here is my code这是我的代码
public static Bitmap ChangeColor(Bitmap scrBitmap)
{
Color newColor = Color.Red;
Color actualColor;
Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
for (int i = 0; i < scrBitmap.Width; i++)
{
for (int j = 0; j < scrBitmap.Height; j++)
{
actualColor = scrBitmap.GetPixel(i, j);
if (actualColor.R == 0 && actualColor.G == 0 && actualColor.B == 0)
newBitmap.SetPixel(i, j, Color.FromArgb(actualColor.A, Color.Red));
}
}
return newBitmap;
}
On Load负载
Bitmap image = new Bitmap(@"D:\test.jpg");
pictureBox1.Image = ChangeColor(image);
I just want to change the color of the black background to red but it's not working.我只想将黑色背景的颜色更改为红色,但它不起作用。 What am I missing?我错过了什么?
Edit: I tried the solution of This Post but it changes the color of the whole image.编辑:我尝试了这篇文章的解决方案,但它改变了整个图像的颜色。
Edit2: I tried @JonasH solution Edit2:我尝试了@JonasH 解决方案
if (0.3 * actualColor.R + 0.59 * actualColor.G + 0.11 * actualColor.B < 10)
newBitmap.SetPixel(i, j, Color.FromArgb(actualColor.A, Color.Red));
else
newBitmap.SetPixel(i, j, actualColor);
It worked but not perfectly.它有效,但并不完美。 Some pixels which are not pure black but close enough to black are still not changed.一些不是纯黑色但足够接近黑色的像素仍然没有改变。 Here is the这里是
The most obvious problem is that you create a new bitmap, but do not copy the color for non black pixels.最明显的问题是您创建了一个新的 bitmap,但不要复制非黑色像素的颜色。 So you probably should do:所以你可能应该这样做:
if (actualColor.R == 0 && actualColor.G == 0 && actualColor.B == 0)
newBitmap.SetPixel(i, j, Color.FromArgb(actualColor.A, Color.Red));
else
newBitmap.SetPixel(i, j, actualColor);
An alternative would be to update the source bitmap in-place instead of creating a new one.另一种方法是就地更新源 bitmap 而不是创建新源。
You might also want to change the color checks to something like您可能还想将颜色检查更改为类似
if (0.3 * actualColor.R + 0.59 * actualColor.G + 0.11*actualColor.B < threshold)
To include all pixels with a luminosity lower than some threshold包括亮度低于某个阈值的所有像素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.