System.Drawing.Bitmap.MakeTransparent C# (CSharp) Method

MakeTransparent() public method

public MakeTransparent ( Color transparentColor ) : void
transparentColor Color
return void
        public void MakeTransparent(Color transparentColor)
        {
            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 = GetPixelFormatComponents (pixelFormat);
            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);
        }

Same methods

Bitmap::MakeTransparent ( ) : void

Usage Example

 /// <summary>
 /// Constructor of a true false column that creates a column
 /// using, be default, a check mark for true and no image for false values.
 /// </summary>
 /// <param name="field">The field within a dataview to use for the column.</param>
 /// <param name="maxWidth">The maximum width for this column</param>
 public ReportBoolColumn(string field, float maxWidth)
     : base(field, maxWidth)
 {
     Bitmap trueBmp = new Bitmap (GetType(), DefaultTrueImageName);
     trueBmp.MakeTransparent ();
     TrueImage = trueBmp;
 }
All Usage Examples Of System.Drawing.Bitmap::MakeTransparent