05
2013
06

asp.net 使用处理程序生成带有logo的二维码

首先建一个asp.net页面,里面包含生成所需的logo上传file控件:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="QrLogCode.aspx.cs" Inherits="AdminTest_QrLogCode" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>二维码生成工具(带log)</title>
    <script type="text/javascript" src="../Jscript/admin/jquery-1.4.2.js"></script>
    <script src="../Jscript/admin/jquery.form.js" type="text/javascript"></script>
    <style type="text/css">
        .style1
        {
            width: 100%;
            min-width: 800px;
            text-align: left;
        }
        .txt
        {
            width: 40%;
        }
    </style>
</head>
<body>
    <form id="form1" enctype="multipart/form-data">
    <div>
        <table class="style1">
            <tr>
                <td style="text-align: right; width: 20%;">
                    输入要生成二维码的内容:
                </td>
                <td>
                    <input type="text" id="txt_qr" name="txt_qr" value="https://www.zhengdecai.com/" class="txt" />&nbsp;&nbsp;&nbsp;&nbsp;<span>请使用生成“<a
                        href="BarCode.aspx">条形码</a>”</span>
                </td>
            </tr>
            <tr>
                <td style="text-align: right;">
                    二维码图片:
                </td>
                <td>
                    <img id="qrimg" alt="二维码图片" src="../images/20130424105224.jpg" />
                </td>
            </tr>
            <tr>
                <td style="text-align: right;">
                    log图片:
                </td>
                <td>
                    <input type="file" id="fileLog" name="fileLog" /> 
                </td>
            </tr>
            <tr>
                <td style="text-align: right;">
                    尺寸大小:
                </td>
                <td>
                    <input id="txt_size" name="txt_size" type="text" value="4" class="txt" />
                </td>
            </tr>
            <tr>
                <td colspan="4">
                    <div style="text-align: left; padding-left: 200px; margin-top: 50px;">
                        <input id="btnSubmit" type="button" value="生成二维码" /></div>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    $(function () {
        $("#btnSubmit").click(function () {
            /*if ($("[id$='fileLog']").val() == "") {
            alert("请选择log图片的文件!");
            return false;
            }*/
            var txt_qr = $("#txt_qr").val();
            var txt_size = $("#txt_size").val();
            $("[id$='form1']").ajaxSubmit({
                url: "../AjaxUrl/Admin/QrLogCode.ashx",
                type: "post",
                dataType: 'text',
                resetForm: "true",
                success: function (data) {
                    var dataObj = data;
                    if ($(dataObj).text() != "") {
                        $("#qrimg").attr("src", "../File/" + $(dataObj).text());
                    }
                    else {
                        $("#qrimg").attr("src", "../File/" + dataObj);
                    }
                    $("#txt_qr").val(txt_qr);
                    $("#txt_size").val(txt_size);
                },
                error: function (request, message, ex) {
                    alert("错误:" + message);
                }
            });
        });
    });
</script>

建一个一般处理程序进行生成二维码图片和logo图片,把logo图片水印到二维码图片上,得到带有logo的二维码

<%@ WebHandler Language="C#" Class="QrLogCode" %>

using System;
using System.Web;

using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Collections; 
using System.Web.Services;

public class QrLogCode : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        int resultVal = (int)ReturnVal.Failed;
        string fileAbsPath = "";
        string filename = "";
        string filepath = "";
        try
        {
            HttpPostedFile myFile = context.Request.Files["fileLog"];

            if (myFile != null)
            {
                if (myFile.InputStream.Length != 0)
                {
                    string originalFileName = Path.GetExtension(myFile.FileName);     //原文件名
                    string newFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + originalFileName;
                    fileAbsPath = context.Server.MapPath(@"~\File") + "\\" + newFileName;   //绝对路径

                    myFile.SaveAs(fileAbsPath);

                    resultVal = (int)ReturnVal.Succeed;
                }
                else
                {
                    resultVal = (int)ReturnVal.FileEmpty;
                }
            }
            else
            {
                resultVal = (int)ReturnVal.NotSelected;
            }
        }
        catch (Exception)
        {
            resultVal = (int)ReturnVal.Failed;
        }

        string txt_qr = ConverToGB(context.Request["txt_qr"].ToString().Trim(), 16);
        string qrEncoding = "Byte";
        string Level = "M";
        string txt_ver = "7";
        string txt_size = context.Request["txt_size"].ToString();

        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
        String encoding = qrEncoding;
        if (encoding == "Byte")
        {
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
        }
        try
        {
            int scale = Convert.ToInt16(txt_size);
            qrCodeEncoder.QRCodeScale = scale;
        }
        catch (Exception ex)
        {
            return;
        }
        try
        {
            int version = Convert.ToInt16(txt_ver);
            qrCodeEncoder.QRCodeVersion = version;
        }
        catch (Exception ex)
        {
            return;
        }
        string errorCorrect = Level;
        if (errorCorrect == "L")
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;

        Image image;
        String data = txt_qr;
        image = qrCodeEncoder.Encode(data);
        filename = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
        filepath = context.Server.MapPath(@"~\File") + "\\" + filename;
        System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
        image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
        fs.Close();
        image.Dispose();
        if (resultVal == 1)
        {
            string imgFile = ImageWatermark(filepath, fileAbsPath, 30);
            if (File.Exists(fileAbsPath))
            {
                File.Delete(fileAbsPath);
            }
            if (File.Exists(imgFile))
            {
                File.Delete(imgFile);
            }
        }
        context.Response.Clear();
        context.Response.Write(filename.Trim());
    }

    #region 返回值
    /// <summary>
    /// 返回值
    /// </summary>
    private enum ReturnVal : int
    {
        /// <summary>
        /// 不能上传 0 K大小的文件
        /// </summary>
        FileEmpty = -2,

        /// <summary>
        /// 未选中文件
        /// </summary>
        NotSelected = -1,

        /// <summary>
        /// 上传失败
        /// </summary>
        Failed = 0,

        /// <summary>
        /// 成功
        /// </summary>
        Succeed = 1
    }
    #endregion


    /// <summary>  
    /// 10进制或16进制转换为中文  
    /// </summary>  
    /// <param name="name">要转换的字符串</param>  
    /// <param name="fromBase">进制(10或16)</param>  
    /// <returns></returns>  
    public string ConverToGB(string text, int fromBase)
    {
        string value = text;
        MatchCollection mc;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        switch (fromBase)
        {
            case 10:

                MatchCollection mc1 = Regex.Matches(text, @"&#([\d]{5})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                foreach (Match _v in mc1)
                {
                    string w = _v.Value.Substring(2);
                    w = Convert.ToString(int.Parse(w), 16);
                    byte[] c = new byte[2];
                    string ss = w.Substring(0, 2);
                    int c1 = Convert.ToInt32(w.Substring(0, 2), 16);
                    int c2 = Convert.ToInt32(w.Substring(2), 16);
                    c[0] = (byte)c2;
                    c[1] = (byte)c1;
                    sb.Append(Encoding.Unicode.GetString(c));
                }
                value = sb.ToString();

                break;
            case 16:
                mc = Regex.Matches(text, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (mc != null && mc.Count > 0)
                {

                    foreach (Match m2 in mc)
                    {
                        string v = m2.Value;
                        string w = v.Substring(2);
                        byte[] c = new byte[2];
                        int c1 = Convert.ToInt32(w.Substring(0, 2), 16);
                        int c2 = Convert.ToInt32(w.Substring(2), 16);
                        c[0] = (byte)c2;
                        c[1] = (byte)c1;
                        sb.Append(Encoding.Unicode.GetString(c));
                    }
                    value = sb.ToString();
                }
                break;
        }
        return value;
    }

    /// <summary>
    /// 图片水印处理方法
    /// </summary>
    /// <param name="path">需要加载水印的图片路径(绝对路径)</param>
    /// <param name="waterpath">水印图片(绝对路径)</param>
    /// <param name="waterpath">水印图片最大宽度</param>
    /// <returns></returns>
    private string ImageWatermark(string path, string waterpath, int maxW)
    {
        //获取文件扩展名
        string kz_name = Path.GetExtension(path);
        string fileNames = "";
        //暂时只支持给.JPG,.BMP,.JPEG格式加水印
        if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg" || kz_name == ".png" || kz_name == ".gif")
        {
            //设置新的文件名
            DateTime time = DateTime.Now;
            string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString();
            //加载需要加载水印的图片
            Image img = Bitmap.FromFile(path);
            //加载水印图片
            Image waterimg = Image.FromFile(waterpath);

            //添加水印
            Graphics g = Graphics.FromImage(img);
            //获取水印位置设置
            ArrayList loca = new ArrayList();
            int x = 0;
            int y = 0;
            int width = maxW;
            int height = waterimg.Height / (waterimg.Width / maxW);

            int cH = 0;
            if (height < maxW)
            {
                cH = maxW - height;
            }

            x = img.Width / 2 - width / 2;
            y = img.Height / 2 - height / 2 + cH / 2;
            loca.Add(x);
            loca.Add(y);

            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;    //这里是矩形框居中
            sf.LineAlignment = StringAlignment.Center;  //这里是文本居中

            g.DrawImage(waterimg, new Rectangle(int.Parse(loca[0].ToString()), int.Parse(loca[1].ToString()), width, height));
            //释放资源
            waterimg.Dispose();
            g.Dispose();
            //保存水印图片
            string newpath = Path.GetDirectoryName(path) + "\\" + filename + kz_name;
            fileNames = filename + kz_name;
            img.Save(newpath);
            img.Dispose();
            //将水印复制到原有图片
            //将水印图片替换原有图片
            File.Copy(newpath, path, true);
            //删除水印
            if (File.Exists(newpath))
            {
                File.Delete(newpath);
            }
        }
        else
        {
            fileNames = "";
        }
        return fileNames;
    }

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

显示效果:

image

« 上一篇下一篇 »

评论列表:

1.淘金客  2013/6/24 14:30:31 回复该留言
好东西啊 但是我还是看不懂
2.赵子安博客  2013/7/4 19:00:14 回复该留言
来支持下,以后多多向博主学习。
3.长安婚纱摄影  2013/7/11 16:18:15 回复该留言
学习了,谢谢博主的分享。
4.松岗婚纱摄影  2013/7/11 17:34:55 回复该留言
不错哦
5.月经不调  2013/12/27 16:32:42 回复该留言
谢谢分享,学习了。等会手动试试
6.护栏网  2014/3/15 10:29:34 回复该留言
刚刚说过

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。