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");

            }
        }


 
    }
}