位图上的着色不准确(我已经看过:如何在C#.NET中更改图像的像素颜色) [英] Coloring on bitmap not accurate (i already looked at: How to Change Pixel Color of an Image in C#.NET)
问题描述
我想做的是在事件发生后,我将所有箭头图片设置为紫色.
What I am trying to do is after a event happens i set all my arrow pictures to purple.
这是我的箭头图片在绘制之前的样子:
Here is what my arrow picture looks like before drawing:
这是绘制后的样子:
Here is what it looks like after drawing:
首先,我用箭头列出所有图片框:
First I make a list of all the pictureboxes with the arrow:
List<PictureBox> arrows = new List<PictureBox>();
foreach (var item in Controls.OfType<PictureBox>())
{
if (item.Name.StartsWith("arrow"))
{
arrows.Add(item);
}
}
这是我用来给图片着色的代码:
And this is the code I use to color the pictures:
System.Drawing.Color purple = System.Drawing.Color.Purple;
foreach (var item in arrows)
{
Bitmap bmp = new Bitmap(item.Image, item.Height, item.Width);
for (int i = 0; i < item.Height; i++)
{
for (int j = 0; j < item.Width; j++)
{
var actualColor = bmp.GetPixel(i, j).ToArgb();
var purpleA = bmp.GetPixel(i, j).A;
if (actualColor != System.Drawing.Color.White.ToArgb())
{
bmp.SetPixel(i, j, System.Drawing.Color.FromArgb(purpleA, purple));
} else
{
bmp.SetPixel(i, j, System.Drawing.Color.FromArgb(actualColor));
}
}
}
item.Image = bmp;
}
如何准确为图像着色?此刻紫色的确很烂.我需要它与黑色箭头完全相同,但不是黑色,我需要紫色.
How can I color the image accurately? At the moment the purple is really badly drawn. I need it to be the exact same as the black arrow but instead of black I need it to be purple.
注意:将黑色箭头图像放在图片框中时,我会调整其大小,因此在形式上,黑色箭头和紫色箭头的大小相同.我上传了带有屏幕截图的紫色箭头,而黑色箭头来自我的计算机.这就是为什么它们的大小不一样.
Note: I resize the black arrow image when I put it in the picturebox, so on the form the black and the purple arrow are the same size. I uploaded the purple arrow with a screenshot and the black arrow was from my computer. That's why they are not the same size.
推荐答案
您可以使用颜色映射表将颜色替换为另一种颜色.它比循环每个像素快得多.
You could use the color map to replace a color by another one. it's much faster than looping for each pixels.
Graphics g = pictureBox.GetGraphics; // get the picture box graphics (i doubt this line compile but you get the idea of the object you need)
using (Bitmap bmp = new Bitmap("img.bmp")) // or the image currently in the picture box
{
// create the color map
var colorMap = new ColorMap[1];
colorMap[0] = new ColorMap();
// old color
colorMap[0].OldColor = Color.Black;
// replaced by this color
colorMap[0].NewColor = Color.Purple;
// attribute to remap the table of colors
var att = new ImageAttributes();
att.SetRemapTable(colorMap);
// draw result
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
g.DrawImage(bmp, rect, 0, 0, rect.Width, rect.Height, GraphicsUnit.Pixel, att);
}
这篇关于位图上的着色不准确(我已经看过:如何在C#.NET中更改图像的像素颜色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!