Asp.Net 合并图片(二维码和其他图片合并)

需求:根据网址生成二维码,然后再把二维码生成到背景图片上,然后显示在网页中

pic.ashx

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

using System;
using System.Web;
using ThoughtWorks.QRCode.Codec;
using System.IO;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;
public class GetHongbao : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        string iid = context.Request.QueryString["id"];
        string url = "http://www.ceshi.com/tg" + iid;
        string bg = context.Server.MapPath("/images/hb.png");
        Image imgNew = CombinImage(bg, url);

        MemoryStream ms = new MemoryStream();
        imgNew.Save(ms, ImageFormat.Png);
        imgNew.Dispose();

        context.Response.ClearContent();
        context.Response.ContentType = "image/png";
        context.Response.BinaryWrite(ms.ToArray());
        context.Response.End();
        
    }

    public Image CombinImage(string sourceImg,string url)
    {
        Image imgBack = Image.FromFile(sourceImg);     //相框图片  

        //从指定的System.Drawing.Image创建新的System.Drawing.Graphics        
        Graphics g = Graphics.FromImage(imgBack);

        //g.DrawImage(imgBack, 0, 0, 148, 124);      // g.DrawImage(imgBack, 0, 0, 相框宽, 相框高); 
        //g.FillRectangle(System.Drawing.Brushes.Black, 16, 16, (int)112 + 2, ((int)73 + 2));//相片四周刷一层黑色边框


        g.DrawImage(GetQcode(url), 415, 798, 670, 670);
        GC.Collect();
        return imgBack;
    }
    public Image GetQcode(string data)
    {
        //初始化二维码生成工具
        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
        qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//二维码编码(Byte、AlphaNumeric、Numeric)
        qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;//二维码纠错能力(L:7% M:15% Q:25% H:30%)
        qrCodeEncoder.QRCodeVersion = 0;//二维码密集度0-40
        qrCodeEncoder.QRCodeScale = 20;//二维码尺寸(Version为0时,1:30x30,每加1宽和高各加29

        return qrCodeEncoder.Encode(data, Encoding.Default);
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}

//需要使用到二维码ThoughtWorks.QRCode.dll

html调用

<img src="pic.ashx?id=1" />

posted @ 2019-03-06 16:58  WebApi  阅读(1508)  评论(0编辑  收藏  举报
CopyRight © 博客园 WebAPI