Adjust image translucency in C#


The example Use an ImageAttributes object to adjust an image’s brightness in C# uses a ColorMatrix object to scale the red, green, and blue color components of an image’s pixels. You can use a similar technique to scale the pixels’ alpha (opacity) components. For example, if a pixel’s alpha value is 255 (completely opaque) and you scale it by a factor of 0.5, the result is a pixel with alpha = 128 (half transparent).

The following AdjustAlpha method scales an image’s alpha values.

// Adjust an image's translucency.
private Bitmap AdjustAlpha(Image image, float translucency)
    // Make the ColorMatrix.
    float t = translucency;
    ColorMatrix cm = new ColorMatrix(new float[][]
            new float[] {1, 0, 0, 0, 0},
            new float[] {0, 1, 0, 0, 0},
            new float[] {0, 0, 1, 0, 0},
            new float[] {0, 0, 0, t, 0},
            new float[] {0, 0, 0, 0, 1},
    ImageAttributes attributes = new ImageAttributes();

    // Draw the image onto the new bitmap while
    // applying the new ColorMatrix.
    Point[] points =
        new Point(0, 0),
        new Point(image.Width, 0),
        new Point(0, image.Height),
    Rectangle rect =
        new Rectangle(0, 0, image.Width, image.Height);

    // Make the result bitmap.
    Bitmap bm = new Bitmap(image.Width, image.Height);
    using (Graphics gr = Graphics.FromImage(bm))
        gr.DrawImage(image, points, rect,
            GraphicsUnit.Pixel, attributes);

    // Return the result.
    return bm;

The key is the ColorMatrix. It is similar to an identify matrix except the entry that scales the pixels’ alpha components is set to the scale factor t. See the previous post for additional details about how the drawing part works.

If the original image’s pixels all have the same alpha values, then the pixels in the resulting image also have the same alpha components. Normally you would use this method to turn an opaque image (alpha = 255) into a translucent image. However, if the original image has some pixels with different alpha values, the resulting image will also contain pixels with different alpha values. That gives different areas in the image different levels of translucency.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in drawing, graphics, image processing and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.