C# MVC 生成带LOGO的二维码并返回到客户端

使用zxing开源库  

0积分下载地址:http://download.csdn.net/detail/hejisan/9846307

创建二维码并叠加拼合logo的QRCode.cs类:

[csharp]  view plain  copy
  1. using System;  
  2. using System.Drawing;  
  3. using System.Drawing.Drawing2D;  
  4. using System.Drawing.Imaging;  
  5. using ZXing;  
  6. using ZXing.QrCode;  
  7. using ZXing.QrCode.Internal;  
  8.   
  9. namespace HalfBuy.Biz.Utilities  
  10. {  
  11.     public class QRCodeHelper  
  12.     {  
  13.         /// <summary>  
  14.         /// 将图片按一定的比例压缩  
  15.         /// </summary>  
  16.         /// <param name="b">资源图片</param>  
  17.         /// <param name="destHeight">高度</param>  
  18.         /// <param name="destWidth">宽度</param>  
  19.         /// <returns></returns>  
  20.         public static Bitmap GetThumbnail(Bitmap b, int destHeight, int destWidth)  
  21.         {  
  22.             System.Drawing.Image imgSource = b;  
  23.             System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;  
  24.             int sW = 0, sH = 0;  
  25.             // 按比例缩放      
  26.             int sWidth = imgSource.Width;  
  27.             int sHeight = imgSource.Height;  
  28.             if (sHeight > destHeight || sWidth > destWidth)  
  29.             {  
  30.                 if ((sWidth * destHeight) > (sHeight * destWidth))  
  31.                 {  
  32.                     sW = destWidth;  
  33.                     sH = (destWidth * sHeight) / sWidth;  
  34.                 }  
  35.                 else  
  36.                 {  
  37.                     sH = destHeight;  
  38.                     sW = (sWidth * destHeight) / sHeight;  
  39.                 }  
  40.             }  
  41.             else  
  42.             {  
  43.                 sW = sWidth;  
  44.                 sH = sHeight;  
  45.             }  
  46.             Bitmap outBmp = new Bitmap(destWidth, destHeight);  
  47.             Graphics g = Graphics.FromImage(outBmp);  
  48.             g.Clear(Color.Transparent);  
  49.             // 设置画布的描绘质量      
  50.             g.CompositingQuality = CompositingQuality.HighQuality;  
  51.             g.SmoothingMode = SmoothingMode.HighQuality;  
  52.             g.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  53.             g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);  
  54.             g.Dispose();  
  55.             // 以下代码为保存图片时,设置压缩质量      
  56.             EncoderParameters encoderParams = new EncoderParameters();  
  57.             long[] quality = new long[1];  
  58.             quality[0] = 100;  
  59.             EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);  
  60.             encoderParams.Param[0] = encoderParam;  
  61.             imgSource.Dispose();  
  62.             return outBmp;  
  63.         }  
  64.   
  65.         /// <summary>  
  66.         /// 生成二维码  
  67.         /// </summary>  
  68.         /// <param name="content">需要生成二维码的内容</param>  
  69.         /// <param name="size">二维码图片长宽大小</param>  
  70.         /// <returns></returns>  
  71.         public static Bitmap Create(string content, int size)  
  72.         {  
  73.             try  
  74.             {  
  75.                 var options = new QrCodeEncodingOptions  
  76.                 {  
  77.                     DisableECI = true,  
  78.                     CharacterSet = "UTF-8",  
  79.                     Width = size,  
  80.                     Height = size,  
  81.                     Margin = 0,  
  82.                     ErrorCorrection = ErrorCorrectionLevel.H  
  83.                 };  
  84.                 var writer = new BarcodeWriter();  
  85.                 writer.Format = BarcodeFormat.QR_CODE;  
  86.                 writer.Options = options;  
  87.                 var bmp = writer.Write(content);  
  88.                 return bmp;  
  89.             }  
  90.             catch (Exception ex)  
  91.             {  
  92.                 return null;  
  93.             }  
  94.         }  
  95.  
  96.         #region 合并用户QR图片和用户头像  
  97.   
  98.         /// <summary>     
  99.         /// 合并用户QR图片和用户头像     
  100.         /// </summary>     
  101.         /// <param name="qrImg">QR图片(二维码图片)</param>     
  102.         /// <param name="headerImg">用户头像</param>     
  103.         /// <param name="n">缩放比例</param>     
  104.         /// <returns></returns>     
  105.         public static Bitmap MergeQrImg(Bitmap qrImg, Bitmap headerImg, double n = 0.23)  
  106.         {  
  107.             int margin = 10;  
  108.             float dpix = qrImg.HorizontalResolution;  
  109.             float dpiy = qrImg.VerticalResolution;  
  110.             var _newWidth = (10 * qrImg.Width - 46 * margin) * 1.0f / 46;  
  111.             var _headerImg = ZoomPic(headerImg, _newWidth / headerImg.Width);  
  112.             //处理头像     
  113.             int newImgWidth = _headerImg.Width + margin;  
  114.             Bitmap headerBgImg = new Bitmap(newImgWidth, newImgWidth);  
  115.             headerBgImg.MakeTransparent();  
  116.             Graphics g = Graphics.FromImage(headerBgImg);  
  117.             g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  
  118.             g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;  
  119.             g.Clear(Color.Transparent);  
  120.             Pen p = new Pen(new SolidBrush(Color.White));  
  121.             Rectangle rect = new Rectangle(0, 0, newImgWidth - 1, newImgWidth - 1);  
  122.             using (GraphicsPath path = CreateRoundedRectanglePath(rect, 7))  
  123.             {  
  124.                 g.DrawPath(p, path);  
  125.                 g.FillPath(new SolidBrush(Color.White), path);  
  126.             }  
  127.             //画头像     
  128.             Bitmap img1 = new Bitmap(_headerImg.Width, _headerImg.Width);  
  129.             Graphics g1 = Graphics.FromImage(img1);  
  130.             g1.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  
  131.             g1.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;  
  132.             g1.Clear(Color.Transparent);  
  133.             Pen p1 = new Pen(new SolidBrush(Color.Gray));  
  134.             Rectangle rect1 = new Rectangle(0, 0, _headerImg.Width - 1, _headerImg.Width - 1);  
  135.             using (GraphicsPath path1 = CreateRoundedRectanglePath(rect1, 7))  
  136.             {  
  137.                 g1.DrawPath(p1, path1);  
  138.                 TextureBrush brush = new TextureBrush(_headerImg);  
  139.                 g1.FillPath(brush, path1);  
  140.             }  
  141.             g1.Dispose();  
  142.             PointF center = new PointF((newImgWidth - _headerImg.Width) / 2, (newImgWidth - _headerImg.Height) / 2);  
  143.             g.DrawImage(img1, center.X, center.Y, _headerImg.Width, _headerImg.Height);  
  144.             g.Dispose();  
  145.             Bitmap backgroudImg = new Bitmap(qrImg.Width, qrImg.Height);  
  146.             backgroudImg.MakeTransparent();  
  147.             backgroudImg.SetResolution(dpix, dpiy);  
  148.             headerBgImg.SetResolution(dpix, dpiy);  
  149.             Graphics g2 = Graphics.FromImage(backgroudImg);  
  150.             g2.Clear(Color.Transparent);  
  151.             g2.DrawImage(qrImg, 0, 0);  
  152.             PointF center2 = new PointF((qrImg.Width - headerBgImg.Width) / 2, (qrImg.Height - headerBgImg.Height) / 2);  
  153.             g2.DrawImage(headerBgImg, center2);  
  154.             g2.Dispose();  
  155.             return backgroudImg;  
  156.         }  
  157.  
  158.         #endregion  
  159.  
  160.         #region 图形处理  
  161.   
  162.         /// <summary>     
  163.         /// 创建圆角矩形     
  164.         /// </summary>     
  165.         /// <param name="rect">区域</param>     
  166.         /// <param name="cornerRadius">圆角角度</param>     
  167.         /// <returns></returns>     
  168.         private static GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int cornerRadius)  
  169.         {  
  170.             //下午重新整理下,圆角矩形     
  171.             GraphicsPath roundedRect = new GraphicsPath();  
  172.             roundedRect.AddArc(rect.X, rect.Y, cornerRadius * 2, cornerRadius * 2, 180, 90);  
  173.             roundedRect.AddLine(rect.X + cornerRadius, rect.Y, rect.Right - cornerRadius * 2, rect.Y);  
  174.             roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y, cornerRadius * 2, cornerRadius * 2, 270, 90);  
  175.             roundedRect.AddLine(rect.Right, rect.Y + cornerRadius * 2, rect.Right, rect.Y + rect.Height - cornerRadius * 2);  
  176.             roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y + rect.Height - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);  
  177.             roundedRect.AddLine(rect.Right - cornerRadius * 2, rect.Bottom, rect.X + cornerRadius * 2, rect.Bottom);  
  178.             roundedRect.AddArc(rect.X, rect.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);  
  179.             roundedRect.AddLine(rect.X, rect.Bottom - cornerRadius * 2, rect.X, rect.Y + cornerRadius * 2);  
  180.             roundedRect.CloseFigure();  
  181.             return roundedRect;  
  182.         }  
  183.   
  184.         /// <summary>     
  185.         /// 图片按比例缩放     
  186.         /// </summary>     
  187.         private static Image ZoomPic(Image initImage, double n)  
  188.         {  
  189.             //缩略图宽、高计算     
  190.             double newWidth = initImage.Width;  
  191.             double newHeight = initImage.Height;  
  192.             newWidth = n * initImage.Width;  
  193.             newHeight = n * initImage.Height;  
  194.             //生成新图     
  195.             //新建一个bmp图片     
  196.             System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);  
  197.             //新建一个画板     
  198.             System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);  
  199.             //设置质量     
  200.             newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  
  201.             newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;  
  202.             //置背景色     
  203.             newG.Clear(Color.Transparent);  
  204.             //画图     
  205.             newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);  
  206.             newG.Dispose();  
  207.             return newImage;  
  208.         }  
  209.  
  210.         #endregion  
  211.     }  
  212. }  

MVC  C#控制器方法生成url二维码及从网络请求logo的Action:

[csharp]  view plain  copy
  1. public FileResult GetImage()  
  2.        {  
  3.            string myshareurl = Config.ShareUrl;//+ UserService.myShareParameter();  
  4.            string content = myshareurl;  
  5.            Bitmap bitmap = QRCodeHelper.Create(content, 400);  
  6.            string filename = DateTime.Now.ToFileTime().ToString();  
  7.            Uri uri = new Uri(UserService.SessionUser.headimgurl);  
  8.            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(uri);  
  9.            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();  
  10.            System.IO.Stream resStream = response.GetResponseStream();  
  11.            Bitmap sourcebm = new Bitmap(resStream);//初始化Bitmap图片  
  12.            Bitmap qrAndHeaderBitmap = QRCodeHelper.MergeQrImg(bitmap, sourcebm);  
  13.            System.IO.MemoryStream ms = new System.IO.MemoryStream();  
  14.            qrAndHeaderBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);    
  15.            //qrAndHeaderBitmap.Save(saveFileUrl, System.Drawing.Imaging.ImageFormat.Png);  
  16.            qrAndHeaderBitmap.Dispose(); //释放资源    
  17.            bitmap.Dispose();  
  18.            return new FileContentResult(ms.ToArray(), "image/Png");  
  19.            //or like below     
  20.            //MemoryStream mem = new MemoryStream(image, 0, image.Length);     
  21.            //return new FileStreamResult(mem, "image/jpg");  
  22.        }  

MVC 视图请求图片:

[html]  view plain  copy
  1. <img id="img" src="/User/GetImage" />  

Over!

猜你喜欢

转载自blog.csdn.net/qmdweb/article/details/80774673