You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET MVC中使用ZXing.Net为生成的二维码添加颜色

在ASP.NET MVC中使用ZXing.Net为二维码添加自定义颜色

嘿,我来帮你搞定这个二维码加颜色的问题!其实ZXing.Net的QrCodeEncodingOptions里就自带了设置颜色的属性,不用额外写复杂的绘图代码,直接配置就行。我给你把你的代码修改完善一下:

核心修改:配置颜色属性

你只需要在QrCodeEncodingOptions里添加ForegroundColor(二维码深色内容的颜色)和BackgroundColor(二维码背景色)这两个属性就可以了,示例代码如下:

// 引入必要的命名空间:
// using ZXing;
// using ZXing.QrCode;
// using System.Drawing;

IBarcodeWriter barcodeWriter = new BarcodeWriter
{
    Format = BarcodeFormat.QR_CODE,
    Options = new QrCodeEncodingOptions
    {
        Width = 400,
        Height = 400,
        // 设置二维码前景色(替换成你想要的颜色)
        ForegroundColor = Color.DarkSlateBlue,
        // 设置二维码背景色
        BackgroundColor = Color.LightBlue,
        // 可选:设置边距,避免颜色被裁切
        Margin = 1
    }
};

// 生成带颜色的二维码Bitmap
string qrContent = "你的二维码内容字符串"; // 替换成实际内容
var barcodeBitmap = barcodeWriter.Write(qrContent);

在ASP.NET MVC控制器中返回带颜色的二维码

如果需要在MVC中直接返回二维码图片给前端,可以把这段逻辑写到Controller的Action里,示例如下:

public ActionResult GetColoredQrCode()
{
    // 你的二维码内容,比如链接、文本等
    string qrContent = "https://your-app-url.com";

    IBarcodeWriter barcodeWriter = new BarcodeWriter
    {
        Format = BarcodeFormat.QR_CODE,
        Options = new QrCodeEncodingOptions
        {
            Width = 400,
            Height = 400,
            // 自定义RGB颜色,更灵活
            ForegroundColor = Color.FromArgb(26, 35, 126),
            BackgroundColor = Color.FromArgb(238, 242, 255),
            Margin = 1
        }
    };

    using (Bitmap bitmap = barcodeWriter.Write(qrContent))
    using (MemoryStream ms = new MemoryStream())
    {
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        // 返回PNG格式的图片
        return File(ms.ToArray(), "image/png");
    }
}

额外注意事项

  • 如果你使用的是.NET Core/.NET 5+版本的ASP.NET,需要额外安装ZXing.Net.Bindings.Windows.Compatibility NuGet包,因为System.Drawing在Core环境中需要兼容库支持
  • 颜色支持所有System.Drawing.Color的用法:可以用预设颜色(比如Color.Red)、RGB值、甚至十六进制转RGB
  • 记得处理Bitmap的资源释放,用using语句包裹可以避免内存泄漏

内容的提问来源于stack exchange,提问作者vaishali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:03:31