I am using this code:
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();
}
This code works very well. It changes my white icon image to another color successfully. The problem is: Once I change it, I cannot change it again. It gives me the "Bitmap Region is already locked exception". I am assuming it's because GetPixel() is locking the image?
can anybody suggest a good solution to this problem ?
PS: I understand that GetPixel() is a very slow method, however, I am using 8 image and they are all 24px. They are very small so I don't think GetPixel()'s performance is that big of a problem.
I just tested your code, and it executed correctly (ie I was able to call ColorReplacer multiple times on a single image with different colors each time, and then paint it to a form).
Can you provide a sample of the code you are using that calls your ColorReplacer method?
you need to change the color as per the following process by locking and unlocking the image data:
http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx
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.