0

I want to be able to place an image over an image, but apply a specific level of transparency for the overlaying image.

This is what I have so far:

    private static Image PlaceImageOverImage(Image background, Image overlay, int x, int y, int alpha)
    {
        using (Graphics graphics = Graphics.FromImage(background))
        {
            graphics.CompositingMode = CompositingMode.SourceOver;
            graphics.DrawImage(overlay, new Point(x, y));
        }

        return background;
    }

Any help would be greatly appreciated.

William Troup
  • 12,739
  • 21
  • 70
  • 98
  • Two useful articles: https://msdn.microsoft.com/en-us/library/windows/desktop/ms533952%28v=vs.85%29.aspx (for how to set up the color matrix with an alpha value) and https://msdn.microsoft.com/en-us/library/c78zcz45%28v=vs.110%29.aspx (for how to do it in C#). Or you could go through your overlay image in an unsafe block, setting the alpha value for every pixel. – adv12 Oct 22 '15 at 15:41

1 Answers1

5

You could use a ColorMatrix for this:

private static Image PlaceImageOverImage(Image background, Image overlay, int x, int y, float alpha)
{
    using (Graphics graphics = Graphics.FromImage(background))
    {
        var cm = new ColorMatrix();
        cm.Matrix33 = alpha;

        var ia = new ImageAttributes();
        ia.SetColorMatrix(cm);

        graphics.DrawImage(
            overlay, 
            // target
            new Rectangle(x, y, overlay.Width, overlay.Height), 
            // source
            0, 0, overlay.Width, overlay.Height, 
            GraphicsUnit.Pixel, 
            ia);
    }

    return background;
}

Caution: The alpha is a float (0...1)

PS: I would rather create a new Bitmap and return it, instead of altering an existing one. (and also return it) >>> it's about functional programming.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57