asp.net mvc 生成二维码

本文介绍了一个使用C#实现的二维码生成方法,通过自定义类`QRCodeHelper`实现了字符串到二维码图片的转换过程。该方法利用了`Gma.QrCodeNet.Encoding`库来编码内容并生成二维码图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生成二维码,帮助类:

using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Piano.Utility.Common
{
   public  class QRCodeHelper
    {
        /// <summary>
        /// 获取二维码
        /// </summary>
        /// <param name="strContent">待编码的字符</param>
        /// <param name="ms">输出流</param>
        ///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>
        public static bool GetQRCode(string strContent, MemoryStream ms)
        {
            ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平 
            string Content = strContent;//待编码内容
            QuietZoneModules QuietZones = QuietZoneModules.Two;  //空白区域 
            int ModuleSize = 12;//大小
            var encoder = new QrEncoder(Ecl);
            QrCode qr;
            if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵
            {
                var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones));
                render.WriteToStream(qr.Matrix, ImageFormat.Png, ms);
            }
            else
            {
                return false;
            }
            return true;
        } 
    }
}

使用方法(此处是MVC5.2.0模式下):

 //二维码生成
        public ActionResult getQrCode()
        {

            // Render the QR code as an image
            using (var ms = new MemoryStream())
            {
                string url = string.Format(ConfigurationManager.AppSettings["WxgzhUrl"], UserValidator.GetInstituteId());
                string stringtest = url;
                QRCodeHelper.GetQRCode(stringtest, ms);
                Response.ContentType = "image/Png";
                Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
                Response.End();
            }

            return View();
        }

前端调用:

 <img src="/My/getQrCode" alt="" style="width:160px;height:160px;" /><span class="remindmsg">扫一扫查看</span>

 

转载于:https://www.cnblogs.com/MissQing/p/6477742.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值