位图着色不准确(我已经看过:如何在C#.NET中更改图像的像素颜色)

时间:2016-10-27 12:34:54

标签: c# forms colors bitmap

我想要做的是在事件发生后我将所有箭头图片设置为紫色。

以下是绘制之前我的箭头图片: Arrow to the left

以下是绘图后的样子: Arrow left after collored

首先,我用箭头列出所有图片框:

 List<PictureBox> arrows = new List<PictureBox>();
 foreach (var item in Controls.OfType<PictureBox>())
        {
            if (item.Name.StartsWith("arrow"))
            {
                arrows.Add(item);
            }    
        }

这是我用来为图片着色的代码:

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;
        }

如何准确地为图像着色?目前紫色真的很糟糕。我需要它与黑色箭头完全相同但不是黑色我需要它是紫色。

注意:当我将黑色箭头图像放入图片框时,我会调整它的大小,因此在黑色箭头和紫色箭头的形状上大小相同。我上传了带有屏幕截图的紫色箭头,黑色箭头来自我的电脑。这就是为什么它们的大小不同。

2 个答案:

答案 0 :(得分:0)

控件的尺寸可能与图像不同。

而不是item.Width使用item.Image.Width

EX:

var itemImage = item.Image;
Bitmap bmp = new Bitmap(itemImage, itemImage.Height, itemImage.Width);

答案 1 :(得分:0)

您可以使用颜色贴图将颜色替换为另一种颜色。它比每个像素的循环要快得多。

    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);
    }