繁体   English   中英

如何在 .NET 中叠加图像

[英]How do I overlay an image in .NET

我有一个 .png 图像,我希望覆盖在基本图像上。

我的叠加图像只包含一条红色斜线。 我需要将红线叠加在基本图像上,坐标与叠加图像中的坐标相同。

问题是我没有坐标位置。

我需要使用 C# 以编程方式找到它。覆盖图像将始终是透明的或白色背景。 从叠加图像中找到线坐标的代码是什么?

您可以创建新图像,首先渲染背景图像,然后在其上渲染叠加图像。 由于叠加具有alpha通道,并且线位于应该放置的位置(我的意思是在线的顶部和左侧有不透明的空间),因此不需要坐标。 插图代码:

Image imageBackground = Image.FromFile("bitmap1.png");
Image imageOverlay = Image.FromFile("bitmap2.png");

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));
}
img.Save("output.png", ImageFormat.Png);

如果您使用的是WPF,为什么不使用叠加路径而不是图像(如果它是简单的线条)? 这将允许它缩放到任何大小,并具有操纵其尺寸的方法。

如果您使用的是Winforms,则可以使用一些类似的图形绘制功能 获取图像的尺寸应该很容易,假设您正在使用PictureBox,以下属性应该足够:

myPictureBox.Top
myPictureBox.Bottom
myPictureBox.Left
myPictureBox.Right

同样,对于WPF图像:

myImage.Margin

我已经需要在图像周围创建一个空白区域,并且我使用了 ImageFactory 库来做到这一点。

这是代码。 我猜你有能力弄清楚如何根据你的需要进行调整。

    public static Image ResizedImage(Image image, int desiredWidth, int desiredHeight)
    {
        Image res = (Bitmap)image.Clone();
        Image resizedImage;
        ImageLayer imageLayer = new ImageLayer();
        try
        {
            if (res != null)
            {
                //white background
                res = new Bitmap(desiredWidth, desiredHeight, res.PixelFormat);
                //image to handle
                using (var imgf = new ImageFactory(true))
                {
                    imgf
                        .Load(image)
                        .Resize(new ResizeLayer(new Size(desiredWidth, desiredHeight),
                                                ResizeMode.Max,
                                                AnchorPosition.Center,
                                                false));
                    resizedImage = (Bitmap)imgf.Image.Clone();
                }
                //final image
                if (resizedImage != null)
                {
                    imageLayer.Image = resizedImage;
                    imageLayer.Size = new Size(resizedImage.Width, resizedImage.Height);
                    imageLayer.Opacity = 100;
                    using (var imgf = new ImageFactory(true))
                    {
                        imgf
                            .Load(res)
                            .BackgroundColor(Color.White)
                            .Overlay(imageLayer);
                        res = (Bitmap)imgf.Image.Clone();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Message;
        }
        return res;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM