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

            }
        }


 
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章