如何将两个图像合并为一个图像,将两个图像合并为一个透明而不是第二个图像?

时间:2015-02-10 01:22:11

标签: c# .net winforms

Bitmap bmp1 = new Bitmap(@"c:\coneimages\Cone_Images1.gif");
Bitmap bmp2 = new Bitmap(@"c:\coneimages\PictureBox_Images1.gif");
Bitmap bmp3 = new Bitmap(MergeTwoImages(bmp1,bmp2));
bmp3.Save(@"c:\coneimages\merged.bmp");

public static Bitmap MergeTwoImages(Image firstImage, Image secondImage)
        {
            if (firstImage == null)
            {
                throw new ArgumentNullException("firstImage");
            }

            if (secondImage == null)
            {
                throw new ArgumentNullException("secondImage");
            }

            int outputImageWidth = firstImage.Width > secondImage.Width ? firstImage.Width : secondImage.Width;

            int outputImageHeight = firstImage.Height + secondImage.Height + 1;

            Bitmap outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            using (Graphics graphics = Graphics.FromImage(outputImage))
            {
                graphics.DrawImage(firstImage, new Rectangle(new Point(), firstImage.Size),
                    new Rectangle(new Point(), firstImage.Size), GraphicsUnit.Pixel);
                graphics.DrawImage(secondImage, new Rectangle(new Point(0, firstImage.Height + 1), secondImage.Size),
                    new Rectangle(new Point(), secondImage.Size), GraphicsUnit.Pixel);
            }

            return outputImage;
        }

但那不是我想要的,我不知道在Google中如何寻找和寻找什么。 我想要的是bmp1将像bmp2一样超过bmp2。 bmp1是透明的,我希望它像bmp2上的层。

所以在bmp3中,我会看到整个常规bmp2上有bmp1。

2 个答案:

答案 0 :(得分:2)

假设bmp1中包含alpha,请首先绘制bmp2 ,然后将合成模式设置为SourceOver(默认)绘制bmp1 。这应该完成正确的alpha混合顺序。

换句话说......

Bitmap bmp3 = new Bitmap(MergeTwoImages(bmp2,bmp1)); // Swapped arguments.

如果bmp1不包含alpha,则需要使用颜色矩阵来更改透明度。

答案 1 :(得分:1)

Bitmap m_back = new Bitmap(bmp2.Width, bmp2.Height);
for (int y = 0; y < bmp2.Height; y++)
{
     for (int x = 0; x < bmp2.Width; x++)
     {
          Color temp = Color.FromArgb(80, bmp2.GetPixel(x, y));
          m_back.SetPixel(x, y, temp);
     }
}

Bitmap bmp3 = new Bitmap(MergeTwoImages(bmp1, m_back));