二维码 条形码

参考了:http://blog.csdn.net/smartsmile2012/article/details/17119755

这里写一下二维码和条形码的帮助类。

CodeHelper


首先 通过nuget下载

PS:  这里是ZXing,不是google的那个
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using ThoughtWorks.QRCode.Codec;
using ZXing;
using ZXing.Common;

namespace WebTest
{
    public class Common
    {
        //QRCode
        private static string QRCodeImgUrl_Relative = WebConfigurationManager.AppSettings["QRCodeImgUrl"];
        //BarCode
        private static string BarCodeImgUrl_Relative = WebConfigurationManager.AppSettings["BarCodeImgUrl"];
        //Logo
        private static string LogoImgUrl_Relative = WebConfigurationManager.AppSettings["LogoImgUrl"];

        private static string QRCodeImgUrl = System.Web.HttpContext.Current.Request.MapPath(QRCodeImgUrl_Relative);
        private static string BarCodeImgUrl = System.Web.HttpContext.Current.Request.MapPath(BarCodeImgUrl_Relative);
        private static string LogoImgUrl = System.Web.HttpContext.Current.Request.MapPath(LogoImgUrl_Relative);

        /// <summary>
        /// 二维码
        /// </summary>
        /// <returns></returns>
        public string CreateQRCode(string Code, bool HasLogo = false, int Size = 50)
        {
            Bitmap image = Create_ImgCode(Code, Size);
            System.IO.MemoryStream MStream = new System.IO.MemoryStream();
            image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);

            if (HasLogo)
            {
                System.IO.MemoryStream MStream1 = new System.IO.MemoryStream();
                CombinImage(image, LogoImgUrl).Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);
            }
            string imgPath = SaveImg(QRCodeImgUrl, image);
            return imgPath;
        }

        /// <summary>
        /// 二维码(内存)
        /// </summary>
        /// <returns></returns>
        public MemoryStream CreateQRCodeMS(string Code, bool HasLogo = false, int Size = 50)
        {
            Bitmap image = Create_ImgCode(Code, Size);
            if (HasLogo)
            {
                System.IO.MemoryStream MStream1 = new System.IO.MemoryStream();
                CombinImage(image, LogoImgUrl).Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);
                return MStream1;
            }
            System.IO.MemoryStream MStream = new System.IO.MemoryStream();
            image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);
            return MStream;
        }

        /// <summary>
        /// 条形码(一维码)
        /// </summary>
        /// <returns></returns>
        public string CreateBarCode(string Code)
        {

            string filename = Uri.EscapeUriString(Code) + ".png";//文件名进行encode,防止特殊字符
            string saveFileName = BarCodeImgUrl + filename;
            string httpFileName = BarCodeImgUrl_Relative + filename;
            if (!File.Exists(saveFileName))
            {
                EncodingOptions options = new EncodingOptions();
                options.Width = 2;
                options.Height = 100;
                options.PureBarcode = true;
                BarcodeWriter writer = new BarcodeWriter();
                writer.Options = options;
                writer.Format = BarcodeFormat.CODE_128;

                Bitmap img = writer.Write(Code);
                //判断目录是否存在
                if (!Directory.Exists(BarCodeImgUrl))
                {
                    Directory.CreateDirectory(BarCodeImgUrl);
                }
                img.Save(saveFileName);

            }
            return httpFileName;
        }

        /// <summary>
        /// 条形码(一维码)(内存)
        /// </summary>
        /// <returns></returns>
        public MemoryStream CreateBarCodeMS(string Code)
        {
            MemoryStream ms = new MemoryStream();

            EncodingOptions options = new EncodingOptions();
            options.Width = 2;
            options.Height = 100;
            options.PureBarcode = true;
            BarcodeWriter writer = new BarcodeWriter();
            writer.Options = options;
            writer.Format = BarcodeFormat.CODE_128;

            Bitmap img = writer.Write(Code);
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);


            return ms;
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="img"></param>
        private string SaveImg(string strPath, Bitmap img)
        {
            //保存图片到目录  
            if (!Directory.Exists(strPath))
            {
                Directory.CreateDirectory(strPath);
            }

            //文件名称  
            string guid = Guid.NewGuid().ToString().Replace("-", "") + ".png";
            img.Save(strPath + guid);

            return QRCodeImgUrl_Relative + guid;
        }

        /// <summary>  
        /// 生成二维码图片  
        /// </summary>  
        /// <param name="codeNumber">要生成二维码的字符串</param>       
        /// <param name="size">大小尺寸</param>  
        /// <returns>二维码图片</returns>  
        private Bitmap Create_ImgCode(string codeNumber, int size)
        {
            //创建二维码生成类  
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            //设置编码模式  
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //设置编码测量度  
            qrCodeEncoder.QRCodeScale = size;
            //设置编码版本  
            qrCodeEncoder.QRCodeVersion = 0;
            //设置编码错误纠正  
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //生成二维码图片  
            System.Drawing.Bitmap image = qrCodeEncoder.Encode(codeNumber);
            return image;
        }

        /// <summary>    
        /// 调用此函数后使此两种图片合并,类似相册,有个    
        /// 背景图,中间贴自己的目标图片    
        /// </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 != 200 || img.Width != 200)
            {
                img = KiResizeImage(img, 200, 200, 0);
            }
            Graphics g = Graphics.FromImage(imgBack);

            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);

            g.DrawImage(img, (imgBack.Width - img.Width) / 2, (imgBack.Width - img.Width) / 2, img.Width, img.Height);
            GC.Collect();
            return imgBack;
        }

        /// <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;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


调用方法:


一 ,使用缓存显示图片

前台:

<img style="margin: 5px; width: 230px;" src="GetImg?qrCode=@Model.ListNo">

后台:

public ActionResult GetImg(string qrCode)
        {
            CodeHelper ch = new CodeHelper();
            var q = ch.CreateQRCodeMS(qrCode);
            return File(q.ToArray(), "image/jpeg");
        }


二 ,使用文件显示图片

前台:

<img style="margin: 5px; width: 230px;" src="<%=imgBarCode.ImageUrl %>">

后台:

public void makeQRCode(string code){
           CodeHelper codeHelper=new CodeHelper();
           var imgUrl=codeHelper.CreateQRCode(code,true);
           //全局变量,提供给页面调用
           imgBarCode.ImageUrl = imgUrl;
           
        }


posted @ 2016-12-07 14:17  正怒月神  阅读(307)  评论(0编辑  收藏  举报