Fork me on GitHub
.net求学者

生成二维码(后台、百度和微信)

可用js生成二维码,也可通过后台生成;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ThoughtWorks.QRCode.Codec;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;

namespace MainWeb.Common
{
    /// <summary>
    /// QRCode 的摘要说明
    /// 二维码生成 
    /// 2017-05-09
    /// </summary>
    public class QRCode : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Create_QRCode(context);
        }

        private void Create_QRCode(HttpContext context)
        {
            string strUrl = context.Server.HtmlDecode(context.Request["Url"]);
            string filename = context.Request["filename"];
            int Num = int.Parse(context.Request["Num"]);

            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeScale = 4;
            qrCodeEncoder.QRCodeVersion = 8;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            Image image = qrCodeEncoder.Encode(strUrl);//, System.Text.Encoding.UTF8

            string strIcoPath = context.Server.MapPath("~/" + GetIcoPath(Num));

            //判断浏览器类型 如果是IE文件名转编码
            string curBrowser = context.Request.Browser.Type.ToLower();// HttpContext.Current
            //IE浏览器
            if (curBrowser.IndexOf("explorer", StringComparison.Ordinal) >= 0 ||curBrowser.IndexOf("ie", StringComparison.Ordinal) >= 0)
            {
                filename = context.Server.UrlEncode(filename);
            }

            Image image1 = CombinImage(image, strIcoPath);//Save(Server.MapPath("~/image/") + filename + ".jpg")
            MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            context.Response.ClearContent();
            if (!string.IsNullOrEmpty(filename))
                HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.jpg", filename));
            context.Response.ContentType = "image/Jpeg";
            context.Response.BinaryWrite(ms.ToArray());
            context.Response.End();
            //this.Image1.ImageUrl = "~/image/" + filename + ".jpg";

        }

        /// <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 != 65 || img.Width != 65)
            {
                img = KiResizeImage(img, 65, 65, 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;
        }

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

        private string GetIcoPath(int Num)
        {
            string str = "";
            switch (Num)
            {
                case 1: str = "/GJZ/Images/DataPublish/MEE.bmp"; break;
            }
            return str;
        }

        //     //默认图片大小
        //   int w = 200;
        //   int h = 200;
        //   //默认水印文件
        //   string PrintImg = @"logPrint130_30.png";
        //   switch (ntype)
        //   {
        //       case "4": w = 750; h = 900; PrintImg = "logPrint500_200.png"; break;
        //       case "3": w = 200; h = 150; PrintImg = "logPrint130_30.png"; break;
        //       case "2": w = 120; h = 130; PrintImg = "logPrint130_30.png"; break;
        //   }
        ////增加水印
        //                   comfun.AddWaterPic(ImgFileTemp, Server.MapPath("~") + "/image/" + PrintImg, ImgFile, w, h);
        ///// <summary>
        //   /// 给图片加水印(图片水印)
        //   /// </summary>
        //   /// <param name="strPath">原始文件</param>
        //   /// <param name="strPathSyp">水印文件</param>
        //   /// <param name="strPathSypf">加水印后的结果文件</param>
        //   public static void AddWaterPic(string strPath, string strPathSyp, string strPathSypf, int w, int h)
        //   {
        //       System.Drawing.Image image = System.Drawing.Image.FromFile(strPath);
        //       Bitmap bm = new Bitmap(image, w, h);
        //       System.Drawing.Image copyImage = System.Drawing.Image.FromFile(strPathSyp);
        //       System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
        //       //如果要使水印居中显示,只要更改bm.Width - copyImage.Width, bm.Height - copyImage.Height,这两个值
        //       //就可以了,在实际项目中,我用的是Convert.ToInt32(image.Width * 0.3), Convert.ToInt32(image.Height * 0.3)
        //       g.DrawImage(copyImage, new System.Drawing.Rectangle(bm.Width - copyImage.Width, bm.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
        //       g.Dispose();
        //       copyImage.Dispose();
        //       bm.Save(strPathSypf);
        //       bm.Dispose();
        //       image.Dispose();
        //       //删除临时文件
        //       try
        //       {
        //           File.Delete(strPath);
        //       }
        //       catch { }
        //   }

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

 

var urlMB = 'http://' + window.location.host + "/GJZ/Public/mobile/SitePreview.aspx?MN=";
function GetQRCodeUrl(MN) {
    //var url = 'http://bshare.optimix.asia/barCode?site=weixin&url=' + window.location.host + "/GJZ/Public/mobile/SitePreview.aspx?MN=";
    //var url = 'http://pan.baidu.com/share/qrcode?w=550&h=550&url=' + window.location.host + "/GJZ/Public/mobile/SitePreview.aspx?MN=";
    return '/Common/QRCode.ashx?Num=0&Url=' + encodeURIComponent(urlMB + MN);
}

//判断是否为Trident内核浏览器(IE等)函数
function browserIsIe() {
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        return true;
    }
    else {
        return false;
    }
}
//创建iframe并赋值的函数,传入参数为图片的src属性值.
function createIframe(imgSrc) {
    if (!document.getElementById("IframeReportImg")) {
        //解决IE取消下载再重新下载问题
        //document.all.IframeReportImg.removeNode(true);
        $('<iframe style="display:none;" id="IframeReportImg" name="IframeReportImg" onload="downloadImg(\'' + imgSrc + '\');" width="0" height="0" src="about:blank" ></iframe>').appendTo("body");
    }
    //iframe的src属性如不指向图片地址,则手动修改,加载图片
    if ($('#IframeReportImg').attr("src") != imgSrc) {
        $('#IframeReportImg').attr("src", imgSrc);
    } else {
        //如指向图片地址,IE需重新加载Url
        $('#IframeReportImg').attr("src", imgSrc + "&e=" + new Date().getTime());

        //如指向图片地址,直接调用下载方法
        //downloadImg(imgSrc);
    }
}
//下载图片的函数
function downloadImg(imgSrc) {
    //try {
    //iframe的src属性不为空,调用execCommand(),保存图片
    if ($('#IframeReportImg').src != "about:blank") {
        window.frames["IframeReportImg"].document.execCommand("SaveAs");
    }
    //document.all.IframeReportImg.removeNode(true);
    //}
    //catch (e) {
    //    //SaveAs5(imgSrc);
    //}
    //finally {
    //    document.all.IframeReportImg.removeNode(true);
    //}
}

function bindDownQRCode() {
    //接下来进行事件绑定
    var aBtn = $(".downDiv a");
    if (browserIsIe()) {
        //是ie等,绑定事件
        aBtn.on("click", function () {
            var imgSrc = $(this).attr("rel");
            //IE下需要将文件传入服务端
            if ($(this).attr("filename") != "")
                imgSrc += "&filename=" + encodeURIComponent($(this).attr("filename") + "_qrcode");
            //调用创建iframe的函数
            createIframe(imgSrc);
        });
    }
    else {
        aBtn.each(function (i, v) {
            //支持download,添加属性.
            var imgSrc = $(v).attr("rel");
            $(v).attr("download", $(v).attr("filename") + "_qrcode.jpg");
            $(v).attr("href", imgSrc);
        })
    }
}
//IE浏览器图片保存本地
function savepic(imageUrl) {
    if (document.all.a1 == null) {
        objIframe = document.createElement("IFRAME");
        document.body.insertBefore(objIframe);
        objIframe.outerHTML = "<iframe name=a1 style='width:400px;hieght:300px' src=" + imageUrl + "></iframe>";
        re = setTimeout(function () { savepic(imageUrl) }, 1)
    } else {
        clearTimeout(re)
        pic = window.open(imageUrl, "a1")
        pic.document.execCommand("SaveAs")
        document.all.a1.removeNode(true);
    }
}
//IE浏览器图片保存本地
function SaveAs5(imgURL) {
    var oPop = window.open(imgURL, "鼠标右键另存为保存图片", "width=550, height=550, top=100, left=500");
    oPop.contentWindow.document.body.appendChild("鼠标右键另存为图片");

    myWindow.document.write("鼠标右键另存为图片");
    myWindow.focus();

    for (; oPop.document.readyState != "complete";) {
        if (oPop.document.readyState == "complete") break;
    }
    oPop.document.execCommand("SaveAs");
    oPop.close();
}

 

posted @ 2018-05-10 23:53  hy31337  阅读(1258)  评论(0)    收藏  举报
.net求学者