用另一个透明图像叠加图像

时间:2016-11-29 08:18:19

标签: image-processing

我有两个图像,我想把一个放在另一个上面,让第一个透明。我正在使用此代码,但透明度根本不起作用。第二张图片完全覆盖了第一张图片。我正在使用C#,Framework 4.5,Visual Studio 2012

    static void Main(string[] args)
    { 

        Image imageBackground = Image.FromFile(@"e:\picstest\profile.png");
        Image imageOverlay = SetImageOpacity(Image.FromFile(@"e:\picstest\flag.png"), 50);


        Image img = new Bitmap(imageBackground.Width, imageBackground.Height);

        using (Graphics gr = Graphics.FromImage(img))
        {
            gr.DrawImage(imageBackground, new Point(0, 0));
            gr.DrawImage(imageOverlay, new Point(0, 0));

        }

        string outputFileName = @"e:\picstest\output.png";
        using (MemoryStream memory = new MemoryStream())
        {
            using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
            {
                img.Save(memory, ImageFormat.Jpeg);
                byte[] bytes = memory.ToArray();
                fs.Write(bytes, 0, bytes.Length);
            }
        }

    }

    public static Image SetImageOpacity(Image img, float opacity)
    {
        Bitmap bmp = new Bitmap(img.Width, img.Height); // Determining Width and Height of Source Image
        Graphics graphics = Graphics.FromImage(bmp);
        ColorMatrix colormatrix = new ColorMatrix();
        colormatrix.Matrix33 = opacity;
        ImageAttributes imgAttribute = new ImageAttributes();
        imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
        graphics.Dispose();   // Releasing all resource used by graphics 
        return bmp;
    } 
}
}

1 个答案:

答案 0 :(得分:0)

通过将不透明度值设置为小于1来修复它,显然大于1使其不透明。

相关问题