Beispiel #1
0
        public void MakeTransparent(Color transparentColor)
        {
            // FIXME: Make sure we have an alpha channel
            //MakeSureWeHaveAnAlphaChannel ();

            var colorValues = transparentColor.ElementsRGBA();

            // Lock the bitmap's bits.
            Rectangle rect    = new Rectangle(0, 0, Width, Height);
            var       bmpData = LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                         pixelFormat);

            var alpha = Color.Transparent.A;
            var red   = Color.Transparent.R;
            var green = Color.Transparent.G;
            var blue  = Color.Transparent.B;

            byte alphar = Color.Transparent.A;
            byte redr   = Color.Transparent.R;
            byte greenr = Color.Transparent.G;
            byte bluer  = Color.Transparent.B;

            bool match = false;

            var pixelSize = GetBitsPerPixel(pixelFormat) / 8;

            unsafe
            {
                for (int y = 0; y < Height; y++)
                {
                    byte *row = (byte *)bmpData.Scan0 + (y * bmpData.Stride);
                    for (int x = 0; x < bmpData.Stride; x = x + pixelSize)
                    {
                        redr   = row [x + 2];;
                        greenr = row [x + 1];
                        bluer  = row [x];
                        alphar = row [x + 3];

                        match = false;

                        if (row [x + 2] == colorValues [0] && row [x + 1] == colorValues [1] &&
                            row [x] == colorValues [2] && row [x + 3] == colorValues [3])
                        {
                            match = true;
                        }


                        if (match)
                        {
                            // we process bgra
                            row [x]     = blue;
                            row [x + 1] = green;
                            row [x + 2] = red;

                            if (pixelSize == 4)
                            {
                                row [x + 3] = alpha;
                            }
                        }
                    }
                }
            }

            // Unlock the bits.
            UnlockBits(bmpData);
        }