Java实现的生成二维码统计扫描次数并转发到某个地址功能详解

时间:2021-12-13 21:27:16

本文实例讲述了java实现的生成二维码统计扫描次数并转发到某个地址功能。分享给大家供大家参考,具体如下:

需求:

近几天某个项目需要用户录入个自己的网址,然后系统需要根据用户的的网址生成二维码,然后用户可以拿着它给别人扫描,访问到他录入的网址,在这个过程中.我需要知道用户的二维码被扫描的次数,也就是后面根据其可以做一些扫描排名之类的.

思路:

① 先生成二维码,csdn已经有前辈写了,那么我就直接拿过来用了.
② 将用户的id,和用户录入的网址处理之后作为http get参数封装到二维码中,然后用户扫描会自动跳转到我们系统的某个接口
③ 在接口中根据用户id将用户查询出来,扫描次数加1后重定向到用户录入页面

代码实现:

1. 生成二维码部分,引用了前辈的成果,点个赞,用起来感觉不错!

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package javacommon.qrcode;
import java.awt.color;
import java.awt.graphics2d;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.io.unsupportedencodingexception;
import javax.imageio.imageio;
import org.junit.test;
import jp.sourceforge.qrcode.qrcodedecoder;
import jp.sourceforge.qrcode.exception.decodingfailedexception;
import com.swetake.util.qrcode;
/**
 * 创建二维码工具类,将类改成了静态工具类
 * @author bill
 * @since v1.0 2014/01/07
 */
public class twodimensioncode {
    /*private twodimensioncode() {
    }*/
    /**
     * 生成二维码(qrcode)图片
     * @param content 存储内容
     * @param imgpath 图片路径
     */
    public static void encoderqrcode(string content, string imgpath) {
        encoderqrcode(content, imgpath, "png", 7);
    }
    /**
     * 生成二维码(qrcode)图片
     * @param content 存储内容
     * @param output 输出流
     */
    public static void encoderqrcode(string content, outputstream output) {
        encoderqrcode(content, output, "png", 7);
    }
    /**
     * 生成二维码(qrcode)图片
     * @param content 存储内容
     * @param imgpath 图片路径
     * @param imgtype 图片类型
     */
    public static void encoderqrcode(string content, string imgpath, string imgtype) {
        encoderqrcode(content, imgpath, imgtype, 7);
    }
    /**
     * 生成二维码(qrcode)图片
     * @param content 存储内容
     * @param output 输出流
     * @param imgtype 图片类型
     */
    public static void encoderqrcode(string content, outputstream output, string imgtype) {
        encoderqrcode(content, output, imgtype, 7);
    }
    /**
     * 生成二维码(qrcode)图片
     * @param content 存储内容
     * @param imgpath 图片路径
     * @param imgtype 图片类型
     * @param size 二维码尺寸
     */
    public static void encoderqrcode(string content, string imgpath, string imgtype, int size) {
        try {
            bufferedimage bufimg = qrcodecommon(content, imgtype, size);
            file imgfile = new file(imgpath);
            // 生成二维码qrcode图片
            imageio.write(bufimg, imgtype, imgfile);
        } catch (exception e) {
            e.printstacktrace();
        }
    }
    /**
     * 生成二维码(qrcode)图片
     * @param content 存储内容
     * @param output 输出流
     * @param imgtype 图片类型
     * @param size 二维码尺寸
     */
    public static void encoderqrcode(string content, outputstream output, string imgtype, int size) {
        try {
            bufferedimage bufimg = qrcodecommon(content, imgtype, size);
            // 生成二维码qrcode图片
            imageio.write(bufimg, imgtype, output);
        } catch (exception e) {
            e.printstacktrace();
        }
    }
    /**
     * 生成二维码(qrcode)图片的公共方法
     * @param content 存储内容
     * @param imgtype 图片类型
     * @param size 二维码尺寸 取值范围1-40,值越大尺寸越大,可存储的信息越大
     * @return
     */
    private static bufferedimage qrcodecommon(string content, string imgtype, int size) {
        bufferedimage bufimg = null;
        try {
            qrcode qrcodehandler = new qrcode();
            // 设置二维码排错率,可选l(7%)、m(15%)、q(25%)、h(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
            qrcodehandler.setqrcodeerrorcorrect('m');
            qrcodehandler.setqrcodeencodemode('b');
            // 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大
            qrcodehandler.setqrcodeversion(size);
            // 获得内容的字节数组,设置编码格式
            byte[] contentbytes = content.getbytes("utf-8");
            // 图片尺寸
            int imgsize = 67 + 12 * (size - 1);
            bufimg = new bufferedimage(imgsize, imgsize, bufferedimage.type_int_rgb);
            graphics2d gs = bufimg.creategraphics();
            // 设置背景颜色
            gs.setbackground(color.white);
            gs.clearrect(0, 0, imgsize, imgsize);
            // 设定图像颜色> black
            gs.setcolor(color.black);
            // 设置偏移量,不设置可能导致解析出错
            int pixoff = 2;
            // 输出内容> 二维码
            if (contentbytes.length > 0 && contentbytes.length < 800) {
                boolean[][] codeout = qrcodehandler.calqrcode(contentbytes);
                for (int i = 0; i < codeout.length; i++) {
                    for (int j = 0; j < codeout.length; j++) {
                        if (codeout[j][i]) {
                            gs.fillrect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            } else {
                throw new exception("qrcode content bytes length = " + contentbytes.length + " not in [0, 800].");
            }
            gs.dispose();
            bufimg.flush();
        } catch (exception e) {
            e.printstacktrace();
        }
        return bufimg;
    }
    /**
     * 解析二维码(qrcode)
     * @param imgpath 图片路径
     * @return
     */
    public static string decoderqrcode(string imgpath) {
        // qrcode 二维码图片的文件
        file imagefile = new file(imgpath);
        bufferedimage bufimg = null;
        string content = null;
        try {
            bufimg = imageio.read(imagefile);
            qrcodedecoder decoder = new qrcodedecoder();
            content = new string(decoder.decode(new twodimensioncodeimage(bufimg)), "utf-8");
        } catch (ioexception e) {
            system.out.println("error: " + e.getmessage());
            e.printstacktrace();
        } catch (decodingfailedexception dfe) {
            system.out.println("error: " + dfe.getmessage());
            dfe.printstacktrace();
        }
        return content;
    }
    /**
     * 解析二维码(qrcode)
     * @param input 输入流
     * @return
     */
    public static string decoderqrcode(inputstream input) {
        bufferedimage bufimg = null;
        string content = null;
        try {
            bufimg = imageio.read(input);
            qrcodedecoder decoder = new qrcodedecoder();
            content = new string(decoder.decode(new twodimensioncodeimage(bufimg)), "utf-8");
        } catch (ioexception e) {
            system.out.println("error: " + e.getmessage());
            e.printstacktrace();
        } catch (decodingfailedexception dfe) {
            system.out.println("error: " + dfe.getmessage());
            dfe.printstacktrace();
        }
        return content;
    }
    public static void main(string[] args) {
        string imgpath = "e:/01.png";
        //string encodercontent = "hello 大大、小小,welcome to qrcode!" + "\nmyblog [ http://sjsky.iteye.com ]" + "\nemail [ sjsky007@gmail.com ]";
        twodimensioncode handler = new twodimensioncode();
        //handler.encoderqrcode(encodercontent, imgpath, "png");
//        try {
//            outputstream output = new fileoutputstream(imgpath);
//            handler.encoderqrcode(content, output);
//        } catch (exception e) {
//            e.printstacktrace();
//        }
        // system.out.println("========encoder success");
        string decodercontent = handler.decoderqrcode(imgpath);
        system.out.println("解析结果如下:");
        system.out.println(decodercontent);
        system.out.println("========decoder success!!!");
    }
    @test
    public void test01() throws unsupportedencodingexception{
        string msg = "http://baike.baidu.com/link?yvwkhk4xqvwk444yx444yxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhkikmbrht9-s2wbaebs哈哈哪里拉萨的";
        system.out.println("normal:"+msg.length());
        system.out.println("bytes:"+msg.getbytes("utf-8").length);
        encoderqrcode(msg.tostring(),"e:/2/t7.png", "png", 40);
        system.out.println("ok");
    }
}
package javacommon.qrcode;
import java.awt.image.bufferedimage;
import jp.sourceforge.qrcode.data.qrcodeimage;
public class twodimensioncodeimage implements qrcodeimage {
    bufferedimage bufimg;
    public twodimensioncodeimage(bufferedimage bufimg) {
        this.bufimg = bufimg;
    }
    @override
    public int getheight() {
        return bufimg.getheight();
    }
    @override
    public int getpixel(int x, int y) {
        return bufimg.getrgb(x, y);
    }
    @override
    public int getwidth() {
        return bufimg.getwidth();
    }
}

还有个jar包,点击此处本站下载

2. 生成二维码并且提供外网访问地址方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * 根据用户给的地址,生成一个二维码,并存放到本地. 返回出外网访问地址
 * @param qrcodetargeturl     用户传入的地址
 * @param campaign    活动编号
 * @return
 * @throws unsupportedencodingexception
 */
private string generator2code(string qrcodetargeturl,campaign campaign) throws unsupportedencodingexception {
    // todo 实现二维码创建
    if(!stringutils.isempty(qrcodetargeturl)){
        string httpurl = appconfig.getproperty("filevisiturl");
        string localurl = appconfig.getproperty("uploadfilebasepath");
        // 文件名
        stringbuilder userofurl = new stringbuilder("qrcode/");
        userofurl.append(campaign.getuser().getemail() + "/");
        userofurl.append(campaign.get_id() + "/");
        new file(localurl + userofurl).mkdirs();    // 创建文件夹
        userofurl.append("qrcode.png");
        // 生成扫描地址
        stringbuilder qrcodescannerurl = new stringbuilder();
        {
            qrcodescannerurl.append(appconfig.getproperty("qrcodescannerurl"));
            qrcodescannerurl.append("t="+urlencoder.encode(qrcodetargeturl, "utf-8"));
            qrcodescannerurl.append("&i="+campaign.get_id());
        }
        long targeturllength = qrcodescannerurl.tostring().getbytes("utf-8").length;
        int qrcodesize = 0;
        // 控制生成的二维码大小
        if(targeturllength <= 120 ){         // 7
            qrcodesize = 7;
        }else if(targeturllength <= 410){    // 15
            qrcodesize = 15;
        }else{
            qrcodesize = 20;        // 这里最大20已经能满足需要了,最大可以设置为40
        }
        twodimensioncode.encoderqrcode(
                qrcodescannerurl.tostring(),
                localurl + userofurl,
                "png",
                qrcodesize);
        return httpurl + userofurl;
    }
    return stringutils.empty;
}

3. 扫描生成的所有的二维码会访问的接口,在这里进行扫描统计.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 文件名:qrcodecontroller.java
* 版权:copyright 2014-2015 buyantech.all rights reserved.
* 描述: 负责累加广告的扫描次数
* 修改人:bill
* 修改时间:2014/01/07
* 修改内容: 无
*/package com.buyantech.campaign.controller;
import java.io.ioexception;
import javacommon.base.basespringcontroller;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.apache.commons.lang.stringutils;
import org.apache.log4j.logger;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import com.buyantech.campaign.model.campaign;
import com.buyantech.campaign.service.campaignmanager;
import com.buyantech.campaign.util.appconfig;
/**
 * 负责累加广告的扫描次数
 * @author bill
 * @since v1.0 2014/01/07
 */
@controller
public class qrcodecontroller extends basespringcontroller {
    @autowired
    private campaignmanager campaignmanager;
    logger logger = logger.getlogger(qrcodecontroller.class);
    /**
     * 用作增加广告二维码扫描次数,和转发
     * @param request
     * @param response
     * @throws ioexception
     */
    public void q(httpservletrequest request,httpservletresponse response) throws ioexception{
        string targeturl = request.getparameter("t");        // targerurl : 目标地址
        string camid = request.getparameter("i");        // camid     : 广告编号
        boolean isaddsuccess = false;
        int scannersize = -1;
        if(!stringutils.isempty(camid)){
            campaign campaign = campaignmanager.findbyid(camid);
            if (campaign != null) {
                scannersize = campaign.getqrcodescancount() + 1;
                campaign.setqrcodescancount(scannersize);
                isaddsuccess = true;
                campaignmanager.save(campaign);
            }
        }
        // 判断是否累加成功
        if(!isaddsuccess){
            logger.error("用户扫描目标二维码地址为:"+targeturl+",扫描累加记录失败!");
        }else{
            logger.info("广告编号:"+camid+"被扫描,当前累积次数为:"+scannersize);
        }
        // 判断是否携带地址,理论上是不存在地址为空的.可能被hacker恶意修改,友好提示!
        if(!stringutils.isempty(targeturl)){
            response.sendredirect(targeturl);
        }else{
            response.getwriter().print("<h3>tips:感谢您扫描本次二维码,地址已经失效了,欢迎您访问:<a href=\""+appconfig.getproperty("serverurl")+"\">物联网广告平台</a></h3>");
        }
    }
}

好的,到这里就差不多了.

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/u010811257/article/details/42521325