c# 的二维码 需借助插件ThoughtWorks 

直接引用

using ThoughtWorks.QRCode.Codec;

using ThoughtWorks.QRCode.Codec.Data;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

        //生成二维码方法1

        //text 二维码的文本内容 

       //Counselor对象内含微信头像等信息
        public static string GetTwoCodeMetho(string text, bk_Counselor Counselor)
        {
            String data = text;
            string url = “”;
            if (!string.IsNullOrEmpty(data))
            {

                //声明QRCodeEncoder  其属性在下面的详细方法中有解释
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeScale = 4;
                qrCodeEncoder.QRCodeVersion = 8;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;

                Image image = CreateQRCode(data, QRCodeEncoder.ENCODE_MODE.BYTE, QRCodeEncoder.ERROR_CORRECTION.M, 8, 4, 0, 5);
                //System.Drawing.Image image = qrCodeEncoder.Encode(data);

                System.IO.MemoryStream MStream = new System.IO.MemoryStream();
                image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);
                System.IO.MemoryStream MStream1 = new System.IO.MemoryStream();
                System.Drawing.Image codeimg;
                //有微信头像地址
                if (!string.IsNullOrEmpty(Counselor.CounselorImg))
                {
                    System.Net.WebRequest webreq = System.Net.WebRequest.Create(Counselor.CounselorImg);
                    System.Net.WebResponse webres = webreq.GetResponse();
                    Stream stream = webres.GetResponseStream();
                    Image ImageWeixin;
                    ImageWeixin = Image.FromStream(stream);
                    stream.Close();
                    codeimg = CombinImage(image, ImageWeixin);
                    codeimg.Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    codeimg = image;
                }

                //保存图片到本地
                string PortraitApp = “~/FileLibs/CodeImg/”;
                if (!Directory.Exists(HttpContext.Current.Server.MapPath(PortraitApp)))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(PortraitApp));
                }
                string filename = Counselor.CounselorName + DateTime.Now.ToString(“yyyymmddhhmmssfff”).ToString() + “.png”;
                string filepath = HttpContext.Current.Server.MapPath(PortraitApp) + “\\” + filename;
               
System.IO.FileStream fs = new System.IO.FileStream(filepath,
System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                codeimg.Save(fs, System.Drawing.Imaging.ImageFormat.Png);

               //由于项目前后台分离 需要指定生成二维码后的url
                string RetureFile = System.Configuration.ConfigurationManager.AppSettings[“RetureFile”].ToString();
                url = RetureFile.Replace(“/FileLibs/File/”, “/FileLibs/CodeImg/”) + filename;

                //HttpContext.Current.Response.ClearContent();
                //HttpContext.Current.Response.ContentType = “image/png”;
                //HttpContext.Current.Response.BinaryWrite(MStream1.ToArray());//直接输出图片 测试用

             //处理完释放资源
                //image.Dispose();
                MStream.Dispose();
                MStream1.Dispose();
            }
            return url;
            //HttpContext.Current.Response.Flush();
            //HttpContext.Current.Response.End();
        }

    测试 效果图如下:

     

 

        /// <summary>
        /// 生成二维码  本函数摘录自网友的方法,后面重写了一个
        /// </summary>
        /// <param name=”Content”>内容文本</param>
        /// <param name=”QRCodeEncodeMode”>二维码编码方式</param>
        /// <param name=”QRCodeErrorCorrect”>纠错码等级</param>
        /// <param name=”QRCodeVersion”>二维码版本号 0-40</param>
        /// <param name=”QRCodeScale”>每个小方格的预设宽度(像素),正整数</param>
        /// <param name=”size”>图片尺寸(像素),0表示不设置</param>
        /// <param name=”border”>图片白边(像素),当size大于0时有效</param>
        /// <returns></returns>
       
public static System.Drawing.Image CreateQRCode(string Content,
QRCodeEncoder.ENCODE_MODE QRCodeEncodeMode,
QRCodeEncoder.ERROR_CORRECTION QRCodeErrorCorrect, int QRCodeVersion,
int QRCodeScale, int size, int border)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncodeMode;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeErrorCorrect;
            qrCodeEncoder.QRCodeScale = QRCodeScale;
            qrCodeEncoder.QRCodeVersion = QRCodeVersion;
            System.Drawing.Image image = qrCodeEncoder.Encode(Content);

            #region 根据设定的目标图片尺寸调整二维码QRCodeScale设置,并添加边框
            if (size > 0)
            {
                //当设定目标图片尺寸大于生成的尺寸时,逐步增大方格尺寸
                #region 当设定目标图片尺寸大于生成的尺寸时,逐步增大方格尺寸
                while (image.Width < size)
                {
                    qrCodeEncoder.QRCodeScale++;
                    System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content);
                    if (imageNew.Width < size)
                    {
                        image = new System.Drawing.Bitmap(imageNew);
                        imageNew.Dispose();
                        imageNew = null;
                    }
                    else
                    {
                        qrCodeEncoder.QRCodeScale–; //新尺寸未采用,恢复最终使用的尺寸
                        imageNew.Dispose();
                        imageNew = null;
                        break;
                    }
                }
                #endregion

                //当设定目标图片尺寸小于生成的尺寸时,逐步减小方格尺寸
                #region 当设定目标图片尺寸小于生成的尺寸时,逐步减小方格尺寸
                while (image.Width > size && qrCodeEncoder.QRCodeScale > 1)
                {
                    qrCodeEncoder.QRCodeScale–;
                    System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content);
                    image = new System.Drawing.Bitmap(imageNew);
                    imageNew.Dispose();
                    imageNew = null;
                    if (image.Width < size)
                    {
                        break;
                    }
                }
                #endregion

                //如果目标尺寸大于生成的图片尺寸,则为图片增加白边
                #region 如果目标尺寸大于生成的图片尺寸,则为图片增加白边
                if (image.Width <= size)
                {
                    //根据参数设置二维码图片白边的最小宽度
                    #region 根据参数设置二维码图片白边的最小宽度
                    if (border > 0)
                    {
                       
while (image.Width <= size && size – image.Width < border
* 2 && qrCodeEncoder.QRCodeScale > 1)
                        {
                            qrCodeEncoder.QRCodeScale–;
                            System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content);
                            image = new System.Drawing.Bitmap(imageNew);
                            imageNew.Dispose();
                            imageNew = null;
                        }
                    }
                    #endregion

                    //当目标图片尺寸大于二维码尺寸时,将二维码绘制在目标尺寸白色画布的中心位置
                    if (image.Width < size)
                    {
                        //新建空白绘图
                        System.Drawing.Bitmap panel = new System.Drawing.Bitmap(size, size);
                        System.Drawing.Graphics graphic0 = System.Drawing.Graphics.FromImage(panel);
                        int p_left = 0;
                        int p_top = 0;
                        if (image.Width <= size) //如果原图比目标形状宽
                        {
                            p_left = (size – image.Width) / 2;
                        }
                        if (image.Height <= size)
                        {
                            p_top = (size – image.Height) / 2;
                        }

                        //将生成的二维码图像粘贴至绘图的中心位置
                        graphic0.DrawImage(image, p_left, p_top, image.Width, image.Height);
                        image = new System.Drawing.Bitmap(panel);
                        panel.Dispose();
                        panel = null;
                        graphic0.Dispose();
                        graphic0 = null;
                    }
                }
                #endregion
            }
            #endregion
            return image;
        }

        //生成二维码方法3 text为文本或网址等内容,imgurl则为图片的网址
        public static void GetTwoCodeMethoThree(string text, string imgurl = “”)
        {
            try
            {
                String data = text;
                if (!string.IsNullOrEmpty(data))
                {

                    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//编码方式:BYTE 能支持中文,ALPHA_NUMERIC 扫描出来的都是数
                    qrCodeEncoder.QRCodeScale = 4;//大小:值越大生成的二维码图片像素越高
                    qrCodeEncoder.QRCodeVersion = 8;//版本
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//错误校验、更正等级

                   
Image image = CreateQRCode(text, QRCodeEncoder.ENCODE_MODE.BYTE,
QRCodeEncoder.ERROR_CORRECTION.M, 8, 4, 0, 5);
                    //System.Drawing.Image image = qrCodeEncoder.Encode(data);

                    System.IO.MemoryStream MStream = new System.IO.MemoryStream();
                    image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);
                    System.IO.MemoryStream MStream1 = new System.IO.MemoryStream();
                    System.Drawing.Image codeimg;
                    Image ImageWeixin;
                    if (!string.IsNullOrEmpty(imgurl))
                    {
                        try
                        {

                            //获得网络上的图片
                            System.Net.WebRequest webreq = System.Net.WebRequest.Create(imgurl);
                            System.Net.WebResponse webres = webreq.GetResponse();
                            Stream stream = webres.GetResponseStream();

                            ImageWeixin = Image.FromStream(stream);
                            stream.Close();
      //贴图
                            codeimg = CombinImage(image, ImageWeixin);
                            codeimg.Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);

                        }
                        catch {  }
                    }
                    //codeimg.Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);
                    //string filename = text + DateTime.Now.ToString(“yyyymmddhhmmssfff”).ToString() + “.png”;
                    //string filepath = HttpContext.Current.Server.MapPath(PortraitApp) + “\\” + filename;
                   
//System.IO.FileStream fs = new System.IO.FileStream(filepath,
System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                    //codeimg.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
                    //string RetureFile = System.Configuration.ConfigurationManager.AppSettings[“RetureFile”].ToString();

                    //直接输出图片 不保存
                    HttpContext.Current.Response.ClearContent();
                    HttpContext.Current.Response.ContentType = “image/png”;
                    HttpContext.Current.Response.BinaryWrite(MStream1.ToArray());
                    image.Dispose();
                    MStream.Dispose();
                    MStream1.Dispose();
                }

                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
                //return url;
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ContentType = “text/xml”;
                HttpContext.Current.Response.Write(“操作异常:” + ex.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }

 

       /// <summary>
        /// 调用此函数后使此两种图片合并,类似相册,有个
        /// 背景图,中间贴自己的目标图片,注意参数不同 destImg使用的是已经初始化的Image,可用于网址类的图片
        /// </summary>
        /// <param name=”imgBack”>粘贴的源图片</param>
        /// <param name=”destImg”>粘贴的目标图片</param>
        public static Image CombinImage(Image imgBack, Image destImg, int Lenth = 40)
        {
            Image img = destImg;    //照片图片
            if (img.Height != Lenth || img.Width != Lenth)
            {
                img = KiResizeImage(img, Lenth, Lenth, 0);
                //圆角处理 此处后来优化后调用一次就可以了
                img = CreateRoundedCorner(img, “”, “TopLeft”);
                img = CreateRoundedCorner(img, “”, “TopRight”);
                img = CreateRoundedCorner(img, “”, “BottomLeft”);
                img = CreateRoundedCorner(img, “”, “BottomRight”);
            }
     
            Graphics g = Graphics.FromImage(imgBack);
            g.DrawImage(imgBack, 0, 0, imgBack.Width + 5, imgBack.Height + 5);   //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
           
g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 –
img.Width / 2 – 1, imgBack.Width / 2 – img.Width / 2 – 1, 1,
1);//相片四周刷一层黑色边框
            //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
            g.DrawImage(img, imgBack.Width / 2 – img.Width / 2, imgBack.Width / 2 – img.Width / 2, img.Width, img.Height);

            GC.Collect();//资源释放
            return imgBack;
        }
        /// <summary>
        /// 调用此函数后使此两种图片合并,类似相册,有个
        /// 背景图,中间贴自己的目标图片 参数不同,destImg使用的是本地路径
        /// </summary>
        /// <param name=”imgBack”>粘贴的源图片</param>
        /// <param name=”destImg”>粘贴的目标图片</param>
        public static Image CombinImage(Image imgBack, string destImg)
        {
            Image img = Image.FromFile(destImg);    //照片图片
            if (img.Height != 65 || img.Width != 65)
            {
                img = KiResizeImage(img, 45, 45, 0);
            }
            Graphics g = Graphics.FromImage(imgBack);
            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);   //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
                                                                        
//g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 –
img.Width / 2 – 1, imgBack.Width / 2 – img.Width / 2 –
1,1,1);//相片四周刷一层黑色边框
                                                                         //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
            g.DrawImage(img, imgBack.Width / 2 – img.Width / 2, imgBack.Width / 2 – img.Width / 2, img.Width, img.Height);
            GC.Collect();
            return imgBack;
        }
        //创建图层圆角
        public static Image CreateRoundedCorner(Image image, string sDstFilePath, string sCornerLocation)
        {
            Graphics g = Graphics.FromImage(image);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.CompositingQuality = CompositingQuality.HighQuality;
            Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
            GraphicsPath rectPath = CreateRoundRectanglePath(rect, image.Width / 10, sCornerLocation); //构建圆角外部路径
            Brush b = new SolidBrush(Color.White);//圆角背景白色
            g.DrawPath(new Pen(b), rectPath);
            g.FillPath(b, rectPath);
            g.Dispose();
            //image.Save(sDstFilePath, ImageFormat.Png);            
            return image;
            //image.Dispose();
        }
        //处理圆角 上下左右
        private static GraphicsPath CreateRoundRectanglePath(Rectangle rect, int radius, string sPosition)
        {
            GraphicsPath rectPath = new GraphicsPath();
            switch (sPosition)
            {
                case “TopLeft”:
                    {
                        rectPath.AddArc(rect.Left, rect.Top, radius * 2, radius * 2, 180, 90);
                        rectPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + radius);
                        break;
                    }

                case “TopRight”:
                    {
                        rectPath.AddArc(rect.Right – radius * 2, rect.Top, radius * 2, radius * 2, 270, 90);
                        rectPath.AddLine(rect.Right, rect.Top, rect.Right – radius, rect.Top);
                        break;
                    }

                case “BottomLeft”:
                    {
                        rectPath.AddArc(rect.Left, rect.Bottom – radius * 2, radius * 2, radius * 2, 90, 90);
                        rectPath.AddLine(rect.Left, rect.Bottom – radius, rect.Left, rect.Bottom);
                        break;
                    }

                case “BottomRight”:
                    {
                        rectPath.AddArc(rect.Right – radius * 2, rect.Bottom – radius * 2, radius * 2, radius * 2, 0, 90);
                        rectPath.AddLine(rect.Right – radius, rect.Bottom, rect.Right, rect.Bottom);
                        break;
                    }

            }
            return rectPath;
        }

 

        /// <summary>
        /// Resize图片 裁剪
        /// </summary>
        /// <param name=”bmp”>原始Bitmap</param>
        /// <param name=”newW”>新的宽度</param>
        /// <param name=”newH”>新的高度</param>
        /// <param name=”Mode”>保留着,暂时未用</param>
        /// <returns>处理以后的图片</returns>
        public static Image KiResizeImage(Image bmp, int newW, int newH, int Mode)
        {
            try
            {
                Image b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
               
g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0,
bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();
                return b;
            }
            catch
            {
                return null;
            }
        }

 

//二维码解码

 /// <summary>
        /// 二维码解码
        /// </summary>
        /// <param name=”filePath”>图片路径</param>
        /// <returns></returns>
        public string CodeDecoder(string filePath)
        {
            if (!System.IO.File.Exists(filePath))
                return null;
            Bitmap myBitmap = new Bitmap(Image.FromFile(filePath));
            QRCodeDecoder decoder = new QRCodeDecoder();
            string decodedString = decoder.decode(new QRCodeBitmapImage(myBitmap));
            return decodedString;
        }

图片地址:http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=729f32ebc9cec3fd9f33af36bee1be4a/fd039245d688d43f4c195ed5771ed21b0ef43b61.jpg

例子:http://192.168.2.228/api/Counselor/GetCodeImg?text=sb&imgurl=http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=729f32ebc9cec3fd9f33af36bee1be4a/fd039245d688d43f4c195ed5771ed21b0ef43b61.jpg

 

调用api 生成图片如下

扫码即可得出text的内容

 

版权声明:本文为yaozhiguang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/yaozhiguang/p/7214602.html