首页 > 代码库 > Java生成二维码实现扫描次数统计并转发到某个地址

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

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

思路:

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

代码实现:
1.生成二维码部分,引用了前辈的成果,点个赞,用起来感觉不错!
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
 * @see 源来自: http://blog.csdn.net/wangpeng047/article/details/7181217
 * @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包,附上下载地址:http://pan.baidu.com/s/1jGmoshK


2.生成二维码并且提供外网访问地址方法
<span style="white-space:pre">	</span>/**
	 * 根据用户给的地址,生成一个二维码,并存放到本地. 返回出外网访问地址
	 * @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.扫描生成的所有的二维码会访问的接口,在这里进行扫描统计.
/**
* 文件名: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=http://www.mamicode.com/""+AppConfig.getProperty("serverUrl")+"/">物联网广告平台");>
好的,到这里就差不多了. 

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