在c#中将一个图像重叠为另一个图像透明

时间:2016-07-25 11:42:25

标签: c# winforms overlay transparency

我根据给定图像的注视区域创建热图。我可以创建热图并将其作为新文件保存到我的桌面。但我想创建另一个图像,它由热图和注视的图像组成,用于收集眼动追踪数据。我希望原始图片是纯色背景,然后将热图重叠(或覆盖我不知道)透明,并将它们合并到一个新文件中。有没有办法在c#中做到这一点? 谢谢

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案,

首先我调整背景图片

public static Bitmap ResizeImage(Bitmap image, int width, int height)
    {
        var destRect = new Rectangle(0, 0, width, height);
        var destImage = new Bitmap(width, height);

        destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        using (var graphics = Graphics.FromImage(destImage))
        {
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
            }
        }
        return destImage;
    }

之后,必须将热图设置为另一个不透明度级别,以使背景可见

public static Image SetImageOpacity(Image image, float opacity)
    {
        try
        {
            //create a Bitmap the size of the image provided  
            Bitmap bmp = new Bitmap(image.Width, image.Height);

            //create a graphics object from the image  
            using (Graphics gfx = Graphics.FromImage(bmp))
            {

                //create a color matrix object  
                ColorMatrix matrix = new ColorMatrix();

                //set the opacity  
                matrix.Matrix33 = opacity;

                //create image attributes  
                ImageAttributes attributes = new ImageAttributes();

                //set the color(opacity) of the image  
                attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                //now draw the image  
                gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
            }
            return bmp;
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
            throw ex;
            //return null;
        }
    } 

最后我们需要合并这两个

        public static Image Overlap(Image source1, Image source2)
    {
        var target = new Bitmap(source1.Width, source1.Height, PixelFormat.Format32bppArgb);
        var graphics = Graphics.FromImage(target);
        graphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear

        graphics.DrawImage(source1, 0, 0);
        graphics.DrawImage(source2, 0, 0);

        return target;
    }

这是我的背景: original RTE

这里是合并版本,带有眼球跟踪数据的热图 RTE + heatmap