2

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.

4

2 に答える 2

0

画像データをロックおよびロック解除して、次のプロセスに従って色を変更する必要があります。

http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx

于 2012-12-31T05:27:22.277 に答える
0

コードをテストしたところ、正しく実行されました (つまり、ColorReplacer を 1 つの画像に対して毎回異なる色で複数回呼び出し、フォームにペイントすることができました)。

ColorReplacer メソッドを呼び出すために使用しているコードのサンプルを提供できますか?

于 2012-12-31T05:16:23.763 に答える