我正在使用这段代码:
internal static Image ColorReplacer(Image Img, Color oldcolor, Color newcolor, int tolerence)
{
// Gotten From -> Code Project
Bitmap bmap = (Bitmap)Img.Clone();
Color c;
int iR_Min, iR_Max; int iG_Min, iG_Max; int iB_Min, iB_Max;
//Defining Tolerance
//R
iR_Min = Math.Max((int)oldcolor.R - tolerence, 0);
iR_Max = Math.Min((int)oldcolor.R + tolerence, 255);
//G
iG_Min = Math.Max((int)oldcolor.G - tolerence, 0);
iG_Max = Math.Min((int)oldcolor.G + tolerence, 255);
//B
iB_Min = Math.Max((int)oldcolor.B - tolerence, 0);
iB_Max = Math.Min((int)oldcolor.B + tolerence, 255);
for (int x = 0; x < bmap.Width; x++)
{
for (int y = 0; y < bmap.Height; y++)
{
c = bmap.GetPixel(x, y);
//Determinig Color Match
if ((c.R >= iR_Min && c.R <= iR_Max) &&
(c.G >= iG_Min && c.G <= iG_Max) &&
(c.B >= iB_Min && c.B <= iB_Max)
)
if (newcolor == Color.Transparent)
bmap.SetPixel(x, y, Color.FromArgb(0, newcolor.R, newcolor.G, newcolor.B));
else
bmap.SetPixel(x, y, Color.FromArgb(c.A, newcolor.R, newcolor.G, newcolor.B));
}
}
return (Image)bmap.Clone();
}
此代码运行良好。它成功地将我的白色图标图像更改为另一种颜色。 问题是:一旦我改变了它,我就不能再改变它了。它给了我“Bitmap Region is already locked exception”。我假设这是因为 GetPixel() 正在锁定图像?
谁能提出解决这个问题的好方法?
PS:我知道 GetPixel() 是一个非常慢的方法,但是,我使用的是 8 个图像,它们都是 24px。它们非常小,所以我认为 GetPixel() 的性能不是什么大问题。
请您参考如下方法:
我刚刚测试了您的代码,它执行正确(即,我能够在一张图像上多次调用 ColorReplacer,每次都使用不同的颜色,然后将其绘制到一个表单中)。
您能否提供您正在使用的调用 ColorReplacer 方法的代码示例?
