本地生成二维码(内容为链接)图片

时间:2022-02-22 20:27:59

通过管理NuGet程序包-----QRCoder.dll安装,添加引用就有QRCoder.dll库文件

using QRCoder;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace SYCloud.Framework.Utils.Extension
{
    public static class QRCoderExtension
    {
        public static MemoryStream GetQRCoder(string content)
        {
            QRCodeGenerator qRCodeGenerator = new QRCodeGenerator();
            //QRCodeData qRCodeData = qRCodeGenerator.CreateQrCode(content, 2, false, false, 0, -1);
  QRCodeData qRCodeData = qRCodeGenerator.CreateQrCode(content,QRCodeGenerator.ECCLevel.L, false, false, 0, -1); QRCode qRCode
= new QRCode(qRCodeData); Bitmap graphic = qRCode.GetGraphic(5, Color.Black, Color.White, null, 10, 4, true); MemoryStream memoryStream = new MemoryStream(); graphic.Save(memoryStream, ImageFormat.Jpeg); return memoryStream; } } }

调用如下:

        /// <summary>      
        /// 本地生成二维码图片  
        /// </summary>       
        /// <param name="queryParams"></param> 
        /// <returns></returns>
        public void GetQRCode(NameValueCollection queryParams)
        {
            try
            {
                string folderPath = System.Web.HttpContext.Current.Server.MapPath("~/weboffice/tempfiles/powerOfAttorneyCode");
                if (Directory.Exists(folderPath))
                {
                    Directory.Delete(folderPath, true);
                }
                string powerOfAttorneyId = queryParams["PowerOfAttorneyId"];
                string content = "http://localhost:9999/showORCodeInfo?businessType=EMPOWER&businessKey=" + powerOfAttorneyId;
                //string content = "http://www.baidu.com";
                MemoryStream imgStream = QRCoderExtension.GetQRCoder(content);

                Directory.CreateDirectory(folderPath);

//生成固定尺寸二维码100*100 Image image
= Image.FromStream(imgStream); Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback); Image imgs = image.GetThumbnailImage(100, 100, callb, IntPtr.Zero); imgs.Save(System.Web.HttpContext.Current.Server.MapPath("~/weboffice/tempfiles/powerOfAttorneyCode/qrcode.jpg")); } catch (Exception ex) { throw ex; } } public bool ThumbnailCallback() { return false; }