C#Qrcode生成二维码支持带标题

Posted on 2020-05-24 20:14  月下小王子  阅读(860)  评论(0编辑  收藏  举报

  过程不在叙述,

  1. 通过NuGet进行安装“ThoughtWorks.QRCode”
  2. 生成二维码的方法
    /// <summary>
            /// 生成二维码
            /// </summary>
            /// <param name="enCodeString">二维码内容</param>
            /// <param name="filePath">路径</param>
            /// <param name="qrCodeScale">大小</param>
            /// <returns></returns>
            public static string QRCode(string enCodeString, string filePath = "", int qrCodeScale = 12)
            {
                System.Drawing.Bitmap bt;
    
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//编码方式(注意:BYTE能支持中文,ALPHA_NUMERIC扫描出来的都是数字)
                qrCodeEncoder.QRCodeScale = qrCodeScale;//大小(值越大生成的二维码图片像素越高)
                qrCodeEncoder.QRCodeVersion = 0;//版本(注意:设置为0主要是防止编码的字符串太长时发生错误)
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//错误效验、错误更正(有4个等级)
                qrCodeEncoder.QRCodeBackgroundColor = Color.Black;//背景色
                qrCodeEncoder.QRCodeForegroundColor = Color.White;//前景色
    
    
                bt = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);
    
                string filename = Guid.NewGuid().ToString();
                //string file_path = string.Empty; ;
                if (string.IsNullOrEmpty(filePath))
                {
                    filePath = AppDomain.CurrentDomain.BaseDirectory + "QRCode";
                }
                string codeUrl =$"{filePath}\\{filename}.jpg";
    
                //根据文件名称,自动建立对应目录
                if (!System.IO.Directory.Exists(filePath))
                    System.IO.Directory.CreateDirectory(filePath);
                //bt=KiSetText(bt, "test", 10, 10);
                bt.Save(codeUrl);//保存图片
                return codeUrl;
            }
    

      

     

  3. 如果需要增加标题,则添加方法
    public static Bitmap KiSetText(Bitmap b, string txt, int x, int y)
            {
                if (b == null)
                {
                    return null;
                }
    
                Bitmap resizeImage = new Bitmap(b.Width, b.Height + 40);
                Graphics gfx = Graphics.FromImage(resizeImage);
                gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, 400, 100));
    
                gfx.DrawImageUnscaled(b, 0, 40);
    
                // 作为演示,我们用Arial字体,大小为32,红色。
                FontFamily fm = new FontFamily("Arial");
                Font font = new Font(fm, 24, FontStyle.Regular, GraphicsUnit.Pixel);
                SolidBrush sb = new SolidBrush(Color.Black);
    
                gfx.DrawString(txt, font, sb, new PointF(x, y));
                gfx.Dispose();
    
                return resizeImage;
            }