如何正确居中叠加位图?

发布于 2025-01-09 17:29:26 字数 1345 浏览 1 评论 0原文

我从代码生成 QR 码,然后将其叠加在另一个图像上。问题是它没有按照我的预期排列。

/// <summary>
/// Draw one bitmap over another.
/// </summary>
/// <param name="largeBmp"></param>
/// <param name="smallBmp"></param>
/// <returns></returns>
public Bitmap Superimpose(Bitmap largeBmp, Bitmap smallBmp) {

    Graphics g = Graphics.FromImage(largeBmp);
    g.CompositingMode = CompositingMode.SourceOver;
    
    // Resize it so it fists
    smallBmp = ResizeBitmap(smallBmp, smallBmp.Width / 4, smallBmp.Height / 4);

    var x = (largeBmp.Width -  smallBmp.Width) / 2;
    var y = (largeBmp.Height - smallBmp.Height)/ 2;

    g.DrawImage(smallBmp, new Point(x, y));

    return largeBmp;
}

/// <summary>
/// Resize the bitmap
/// </summary>
/// <param name="bmp"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public Bitmap ResizeBitmap(Bitmap bmp, int width, int height)
{
    Bitmap result = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(result))
    {
        g.DrawImage(bmp, 0, 0, width, height);
    }

    return result;
}

非-对齐图像

I generate a QR code from code, then superimpose it over another image. Thie issue is that it doesn't line up as I expected.

/// <summary>
/// Draw one bitmap over another.
/// </summary>
/// <param name="largeBmp"></param>
/// <param name="smallBmp"></param>
/// <returns></returns>
public Bitmap Superimpose(Bitmap largeBmp, Bitmap smallBmp) {

    Graphics g = Graphics.FromImage(largeBmp);
    g.CompositingMode = CompositingMode.SourceOver;
    
    // Resize it so it fists
    smallBmp = ResizeBitmap(smallBmp, smallBmp.Width / 4, smallBmp.Height / 4);

    var x = (largeBmp.Width -  smallBmp.Width) / 2;
    var y = (largeBmp.Height - smallBmp.Height)/ 2;

    g.DrawImage(smallBmp, new Point(x, y));

    return largeBmp;
}

/// <summary>
/// Resize the bitmap
/// </summary>
/// <param name="bmp"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public Bitmap ResizeBitmap(Bitmap bmp, int width, int height)
{
    Bitmap result = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(result))
    {
        g.DrawImage(bmp, 0, 0, width, height);
    }

    return result;
}

Non-Aligned Image

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱桃奶球 2025-01-16 17:29:26

我在 win forms 项目中尝试了你的代码,代码工作正常,我使用 png 格式来表示大图像和小图像,我认为你应该检查你的 QR 代码,它周围可能有一些空白

在此处输入图像描述

I tried your code in win forms project and code worked fine, I used png format for large and small images, I think you should check your QR code, it might have some blank space around it

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文