NET8下生成二维码

NET8下生成二维码

按网上搜索的总是多少有些问题,得总搜索好几次才能解决的,现把自己用过的可以生成的代码放上来,以备后用

2024年02月20日在 VS2022,NET8,MVC 项目上使用通过

引入NUGET:ZXing.Net.Bindings.ZKWeb.System.Drawing

控制器代码:

using Microsoft.AspNetCore.Mvc;
using System.DrawingCore;
using System.DrawingCore.Imaging;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using ZXing.ZKWeb; 

namespace JCT.Web.Controllers
{
    public class TestController : Controller
    { 
        private Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv;

        public TestController( Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv)
        { 
            this.hostingEnv = hostingEnv;
        }

        public ActionResult Index()
        {
            string text = "http://www.niunan.net";
     
            int width = 300;
            int height = 300;

            int heig = width;
            if (width > height)
            {
                heig = height;
                width = height;
            }
            if (string.IsNullOrWhiteSpace(text))
            {
                return null;
            }
            var w = new QRCodeWriter();
            BitMatrix b = w.encode(text, BarcodeFormat.QR_CODE, width, heig);
            var zzb = new BarcodeWriter();
            zzb.Options = new EncodingOptions()
            {
                Margin = 0,
            };
            Bitmap b2 = zzb.Write(b);

            // 将Bitmap转换为字节数组  

            using (MemoryStream memoryStream = new MemoryStream())
            {

                b2.Save(memoryStream, ImageFormat.Jpeg);

                byte[] imageBytes = memoryStream.ToArray();



                // 设置HTTP响应的Content-Type  

                Response.ContentType = "image/jpeg";



                // 将字节数组写入输出流  

                return File(imageBytes, "image/jpeg");

            }
        }


 
    }
}

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值