Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a System.Drawing.Image semitransparent?

System.Drawing.Graphics.DrawImage pastes one image on another. But I couldn't find a transparency option.

I have already drawn everything I want in the image, I only want to make it translucent (alpha-transparency)

like image 951
Jader Dias Avatar asked Feb 04 '10 15:02

Jader Dias


2 Answers

There is no "transparency" option because what you're trying to do is called Alpha Blending.

public static class BitmapExtensions
{
    public static Image SetOpacity(this Image image, float opacity)
    {
        var colorMatrix = new ColorMatrix();
        colorMatrix.Matrix33 = opacity;
        var imageAttributes = new ImageAttributes();
        imageAttributes.SetColorMatrix(
            colorMatrix,
            ColorMatrixFlag.Default,
            ColorAdjustType.Bitmap);
        var output = new Bitmap(image.Width, image.Height);
        using (var gfx = Graphics.FromImage(output))
        {
            gfx.SmoothingMode = SmoothingMode.AntiAlias;
            gfx.DrawImage(
                image,
                new Rectangle(0, 0, image.Width, image.Height),
                0,
                0,
                image.Width,
                image.Height,
                GraphicsUnit.Pixel,
                imageAttributes);
        }
        return output;
    }
}

Alpha Blending

like image 100
Jack Marchetti Avatar answered Oct 31 '22 19:10

Jack Marchetti


private Image GetTransparentImage(Image image, int alpha)
{
    Bitmap output = new Bitmap(image);

    for (int x = 0; x < output.Width; x++)
    {
        for (int y = 0; y < output.Height; y++)
        {
            Color color = output.GetPixel(x, y);
            output.SetPixel(x, y, Color.FromArgb(alpha, color.R, color.G, color.B));
        }
    }

    return output;
}
like image 2
PCatta Avatar answered Oct 31 '22 19:10

PCatta