使用google的zxing工具在jsp页面中生成二维码以及带logo图标的二维码

1.配置maven的pom文件

<dependency>  
            <groupId>com.google.zxing</groupId>  
            <artifactId>core</artifactId>  
            <version>3.0.0</version>  
        </dependency>  
        
        <dependency>  
            <groupId>com.google.zxing</groupId>  
            <artifactId>javase</artifactId>  
            <version>3.0.0</version>  
        </dependency>  

2.四个二维码的工具类

一个类LogoConfig是设置二维码的logo相关;一个类是ZXingConfig设置二维码的一些参数信息;一个类是生成二维码的,最后一个是对二维码进行解析的可以获取二维码里面的参数信息

package com.teraee.tasystem.util;

import java.awt.Color;

/**
 * 用于二维码生成带logo的配置
 * 
 * @author LH
 */
public class LogoConfig {
    public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;    // logo默认边框颜色
    public static final int IMAGE_WIDTH = 80;//logo一般的宽度
    public static final int IMAGE_HEIGHT = 80;//logo一般的高度
    public static final int DEFAULT_BORDER = 1; // logo默认边框宽度
    public static final int DEFAULT_LOGOPART = 5;   // logo大小默认为照片的1/5
    private final int border = DEFAULT_BORDER;  // 默认边框宽度
    private final Color borderColor;    // 边框颜色
    private final int logoPart; //  边框外围宽度

    /**
     * 二维码无参构造函数 默认设置Logo图片底色白色宽度2
     */
    public LogoConfig() {
        this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
    }

    /**
     * 二维码有参构造函数
     * 
     * @param borderColor 边框颜色
     * @param logoPart 边框宽度
     */
    public LogoConfig(Color borderColor, int logoPart) {
        // 设置边框
        this.borderColor = borderColor;
        // 设置边框宽度
        this.logoPart = logoPart;
    }

    /**
     * 获取边框颜色
     * 
     * @return 获取边框颜色
     */
    public Color getBorderColor() {
        return borderColor;
    }

    /**
     * 获取边框
     * 
     * @return 获取边框
     */
    public int getBorder() {
        return border;
    }

    /**
     * 外围边宽
     * 
     * @return 外围边宽
     */
    public int getLogoPart() {
        return logoPart;
    }
}


package com.teraee.tasystem.util;

import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;

/**
 * 二维码配置信息
 * 
 * @author X-rapido
 * 
 */
public class ZXingConfig {
    private boolean logoFlg = false;    // 是否添加Log图片
    private String content; // 二维码编码内容
    private BarcodeFormat barcodeformat = BarcodeFormat.QR_CODE;    //编码类型
    private int width = 300;    // 生成图片宽度
    private int height = 300;   //  生成图片高度
    private Map<EncodeHintType, ?> hints;   // 设置参数
    private String logoPath;    // Logo图片路径
    private String putPath; // 图片输出路径
    private LogoConfig LogoConfig;  // logo图片参数

    /**
     * 获取 是否添加Log图片
     * 
     * @return logoFlg 是否添加Log图片
     */
    public boolean isLogoFlg() {
        return logoFlg;
    }

    /**
     * 设置 是否添加Log图片
     * 
     * @param logoFlg 是否添加Log图片
     */
    public void setLogoFlg(boolean logoFlg) {
        this.logoFlg = logoFlg;
    }

    /**
     * 获取 二维码编码内容
     * 
     * @return content 二维码编码内容
     */
    public String getContent() {
        return content;
    }

    /**
     * 设置 二维码编码内容
     * 
     * @param content 二维码编码内容
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * 获取 编码类型
     * 
     * @return barcodeformat 编码类型
     */
    public BarcodeFormat getBarcodeformat() {
        return barcodeformat;
    }

    /**
     * 设置 编码类型
     * 
     * @param barcodeformat 编码类型
     */
    public void setBarcodeformat(BarcodeFormat barcodeformat) {
        this.barcodeformat = barcodeformat;
    }

    /**
     * 获取 生成图片宽度
     * 
     * @return width 生成图片宽度
     */
    public int getWidth() {
        return width;
    }

    /**
     * 设置 生成图片宽度
     * 
     * @param width 生成图片宽度
     */
    public void setWidth(int width) {
        this.width = width;
    }

    /**
     * 获取 生成图片高度
     * 
     * @return height 生成图片高度
     */
    public int getHeight() {
        return height;
    }

    /**
     * 设置 生成图片高度
     * 
     * @param height 生成图片高度
     */
    public void setHeight(int height) {
        this.height = height;
    }

    /**
     * 获取 设置参数
     * 
     * @return hints 设置参数
     */
    public Map<EncodeHintType, ?> getHints() {
        return hints;
    }

    /**
     * 设置 设置参数
     * 
     * @param hints 设置参数
     */
    public void setHints(Map<EncodeHintType, ?> hints) {
        this.hints = hints;
    }

    /**
     * 获取 Logo图片路径
     * 
     * @return logoPath Logo图片路径
     */
    public String getLogoPath() {
        return logoPath;
    }

    /**
     * 设置 Logo图片路径
     * 
     * @param logoPath Logo图片路径
     */
    public void setLogoPath(String logoPath) {
        this.logoPath = logoPath;
    }

    /**
     * 获取 图片输出路劲
     * 
     * @return putPath 图片输出路劲
     */
    public String getPutPath() {
        return putPath;
    }

    /**
     * 设置 图片输出路劲
     * 
     * @param putPath 图片输出路劲
     */
    public void setPutPath(String putPath) {
        this.putPath = putPath;
    }

    /**
     * 获取 logoConfig
     * 
     * @return logoConfig logoConfig
     */
    public LogoConfig getLogoConfig() {
        return LogoConfig;
    }

    /**
     * 设置 logoConfig
     * 
     * @param logoConfig logoConfig
     */
    public void setLogoConfig(LogoConfig logoConfig) {
        LogoConfig = logoConfig;
    }

}
package com.teraee.tasystem.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码生成google zxing
 * 
 * @author LH
 * 
 */
public class ZXingCodeUtil {
    /**
     * 二维码图片添加Logo
     * 
     * @param bim 图片流
     * @param logoPic Logo图片物理位置
     * @param logoConfig Logo图片设置参数
     * @throws Exception 异常上抛
     */
    private void addLogo_QRCode(BufferedImage bim, String logoPic, LogoConfig logoConfig) throws Exception {
        try {
            // 对象流传输
            BufferedImage image = bim;
            Graphics2D g = image.createGraphics();

            // 读取Logo图片
            //BufferedImage logo = ImageIO.read(logoPic);
            
            //给logo图片添加背景颜色
            BufferedImage logo = scale(logoPic,logoConfig.IMAGE_HEIGHT ,logoConfig.IMAGE_WIDTH, true);

            // 设置logo的大小,本人设置为二维码图片的20%,因为过大会盖掉二维码
            int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null), heightLogo = logo
                    .getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getWidth(null);

            // 计算图片放置位置
            // logo放在中心
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;
            // 开始绘制图片
            g.drawImage(logo, x, y, widthLogo, heightLogo, null);
            g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
            g.setStroke(new BasicStroke(logoConfig.getBorder()));
            g.setColor(logoConfig.getBorderColor());
            g.drawRect(x, y, widthLogo, heightLogo);

            g.dispose();
            logo.flush();
            image.flush();

        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 二维码的解析
     * 
     * @param image  图片文件流
     * @return 解析后的Result结果集
     * @throws Exception 错误异常上抛
     */
    @SuppressWarnings("unchecked")
    public Result parseQR_CODEImage(BufferedImage image) throws Exception {
        // 设置解析
        Result result = null;
        try {
            MultiFormatReader formatReader = new MultiFormatReader();

            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

            @SuppressWarnings("rawtypes")
            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            result = formatReader.decode(binaryBitmap, hints);

            System.out.println("resultFormat = " + result.getBarcodeFormat());
            System.out.println("resultText = " + result.getText());
        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    /**
     * 生成二维码bufferedImage图片
     * @param zxingconfig 二维码配置信息
     * @return 生成后的 BufferedImage
     * @throws Exception 异常上抛
     */
    public BufferedImage getQR_CODEBufferedImage(ZXingConfig zxingconfig) throws Exception {
        // Google配置文件
        MultiFormatWriter multiFormatWriter = null;
        BitMatrix bm = null;
        BufferedImage image = null;
        try {
            multiFormatWriter = new MultiFormatWriter();

            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            bm = multiFormatWriter.encode(zxingconfig.getContent(), zxingconfig.getBarcodeformat(), zxingconfig.getWidth(), zxingconfig.getHeight(),
                    zxingconfig.getHints());
    		// 读取源图像
            int w = bm.getWidth();
            int h = bm.getHeight();
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            
            
            
            // 开始利用二维码数据创建Bitmap图片,分别设为黑白两色
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }

            // 是否设置Logo图片
            if (zxingconfig.isLogoFlg()) {
                this.addLogo_QRCode(image, zxingconfig.getLogoPath(), zxingconfig.getLogoConfig());
            }
        } catch (WriterException e) {
            throw e;
        }
        return image;
    }

    /**
     * 设置二维码的格式参数
     * 
     * @return
     */
    public Map<EncodeHintType, Object> getDecodeHintType() {
        // 用于设置QR二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 设置QR二维码的纠错级别(H为最高级别)具体级别信息
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置编码方式
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.MAX_SIZE, 350);
        hints.put(EncodeHintType.MIN_SIZE, 100);

        return hints;
    }

    
    /**
	 * 把传入的原始图像按高度和宽度进行缩放,生成符合要求的图标
	 * 
	 * @param srcImageFile
	 *            源文件地址
	 * @param height
	 *            目标高度
	 * @param width
	 *            目标宽度
	 * @param hasFiller
	 *            比例不对时是否需要补白:true为补白; false为不补白;
	 * @throws IOException
	 */
	private static BufferedImage scale(String srcImageFile, int height,int width, boolean hasFiller) throws IOException {
		double ratio = 0.0; // 缩放比例
		File file = new File(srcImageFile);
		BufferedImage srcImage = ImageIO.read(file);
		Image destImage = srcImage.getScaledInstance(width, height,
				BufferedImage.SCALE_SMOOTH);
		// 计算比例
		if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
			if (srcImage.getHeight() > srcImage.getWidth()) {
				ratio = (new Integer(height)).doubleValue()
						/ srcImage.getHeight();
			} else {
				ratio = (new Integer(width)).doubleValue()
						/ srcImage.getWidth();
			}
			AffineTransformOp op = new AffineTransformOp(
					AffineTransform.getScaleInstance(ratio, ratio), null);
			destImage = op.filter(srcImage, null);
		}
		if (hasFiller) {// 补白
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D graphic = image.createGraphics();
			graphic.setColor(Color.white);
			graphic.fillRect(0, 0, width, height);
			if (width == destImage.getWidth(null))
				graphic.drawImage(destImage, 0,
						(height - destImage.getHeight(null)) / 2,
						destImage.getWidth(null), destImage.getHeight(null),
						Color.white, null);
			else
				graphic.drawImage(destImage,
						(width - destImage.getWidth(null)) / 2, 0,
						destImage.getWidth(null), destImage.getHeight(null),
						Color.white, null);
			graphic.dispose();
			destImage = image;
		}
		return (BufferedImage) destImage;
	}
	
    /**
     * 这个工具类 ZXingCodeUtil 是提供二维码图片生成的工具 首先使用的时候需要实例化
     * ZXingCodeUtil 然后实例化参数 ZXingConfig 和 LogoConfig 通过下面的演示可以详细看参数是按照什么循序进行设置 最后调用
     * ZXingCodeUtil 中方法 getQR_CODEBufferedImage来生成二维码
     */
    public static void main(String[] args) throws WriterException {
        String content = "http://www.baidu.com";
        System.out.println("inputParam:" + content);
        try {
            // 生成二维码
            File file = new File("D://55555.png");
            ZXingCodeUtil zp = new ZXingCodeUtil(); // 实例化二维码工具
            ZXingConfig zxingconfig = new ZXingConfig();    // 实例化二维码配置参数
            zxingconfig.setHints(zp.getDecodeHintType());   // 设置二维码的格式参数
            zxingconfig.setContent(content);// 设置二维码生成内容
            zxingconfig.setLogoPath("D://teraLogoV.png"); // 设置Logo图片
            zxingconfig.setLogoConfig(new LogoConfig());    // Logo图片参数设置   
            zxingconfig.setLogoFlg(true);   // 设置生成Logo图片
            BufferedImage bim = zp.getQR_CODEBufferedImage(zxingconfig);// 生成二维码
            ImageIO.write(bim, "png", file);    // 图片写出
            Thread.sleep(500);  // 缓冲

            zp.parseQR_CODEImage(bim);  // 解析调用
            
//            设置图片的背景颜色
//            BufferedImage scaleImage = scale("D://teraLogoV.png", 80,80, true);
//            ImageIO.write(scaleImage, "png", file);    // 图片写出
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

package com.teraee.tasystem.util;

import com.google.zxing.LuminanceSource;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

/**
 * 二维码解析使用类
 * 
 * @author LH
 * 
 */
public class BufferedImageLuminanceSource extends LuminanceSource {
    private final BufferedImage image;
    private final int left;
    private final int top;

    public BufferedImageLuminanceSource(BufferedImage image) {
        this(image, 0, 0, image.getWidth(), image.getHeight());
    }

    public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
        super(width, height);

        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        if (left + width > sourceWidth || top + height > sourceHeight) {
            throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
        }

        for (int y = top; y < top + height; y++) {
            for (int x = left; x < left + width; x++) {
                if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                    image.setRGB(x, y, 0xFFFFFFFF); // = white
                }
            }
        }

        this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
        this.image.getGraphics().drawImage(image, 0, 0, null);
        this.left = left;
        this.top = top;
    }

    @Override
    public byte[] getRow(int y, byte[] row) {
        if (y < 0 || y >= getHeight()) {
            throw new IllegalArgumentException("Requested row is outside the image: " + y);
        }
        int width = getWidth();
        if (row == null || row.length < width) {
            row = new byte[width];
        }
        image.getRaster().getDataElements(left, top + y, width, 1, row);
        return row;
    }

    @Override
    public byte[] getMatrix() {
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];
        image.getRaster().getDataElements(left, top, width, height, matrix);
        return matrix;
    }

    @Override
    public boolean isCropSupported() {
        return true;
    }

    @Override
    public LuminanceSource crop(int left, int top, int width, int height) {
        return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
    }

    @Override
    public boolean isRotateSupported() {
        return true;
    }

    @Override
    public LuminanceSource rotateCounterClockwise() {

        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();

        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);

        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);

        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();

        int width = getWidth();
        return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
    }
}

4.web.xml配置servlet

<servlet>
  	<servlet-name>QRImageServlet</servlet-name>
  	<servlet-class>com.teraee.tasystem.servlet.QRImageServlet</servlet-class>
  </servlet>
<servlet-mapping>
	<servlet-name>QRImageServlet</servlet-name>
	<url-pattern>/servlet/QRImageServlet.servlet</url-pattern>
</servlet-mapping>

5.servlet实现下载二维码

package com.teraee.tasystem.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.teraee.tasystem.util.Constant;
import com.teraee.tasystem.util.Log;
import com.teraee.tasystem.util.LogoConfig;
import com.teraee.tasystem.util.ZXingCodeUtil;
import com.teraee.tasystem.util.ZXingConfig;

/**
 * Servlet implementation class QRImageServlet
 */
@WebServlet("/QRImageServlet")
public class QRImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private static Log log = Log.getLoger(new Object() {
		public Class getClassName() {
			return this.getClass();
		}
	}.getClassName());
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QRImageServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取随机数
		String code=request.getParameter("code");
		log.loger.info("code="+code);
		JSONObject json=new JSONObject();
		json.put("authCode", Constant.AUTH_CODE);
		String imgPath=ServletActionContext.getServletContext().getRealPath("/images/teraLogoV.png");
		try {
			//String content = "http://www.baidu.com";
			ZXingCodeUtil zp = new ZXingCodeUtil(); // 实例化二维码工具
            ZXingConfig zxingconfig = new ZXingConfig();    // 实例化二维码配置参数
            zxingconfig.setHints(zp.getDecodeHintType());   // 设置二维码的格式参数
            zxingconfig.setContent(code);// 设置二维码生成内容
            zxingconfig.setLogoPath(imgPath); // 设置Logo图片的路径
            zxingconfig.setLogoConfig(new LogoConfig());    // Logo图片参数设置   
            zxingconfig.setLogoFlg(true);   // 设置生成Logo图片
            BufferedImage bim = zp.getQR_CODEBufferedImage(zxingconfig);// 生成二维码
            
			ImageIO.write(bim, "png", response.getOutputStream());
			log.loger.info("create QRcode success");
		} catch (Exception e) {
			log.loger.error("create QRcode happen exception "+e);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}

6.前端jsp页面端

//jsp页面代码
<img id="QRCode"  style="height:150px;width:150px" src="" /> 

//生成随机数 uuid的js函数
function generateUUID() {
	  var d = new Date().getTime();
	  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	    var r = (d + Math.random()*16)%16 | 0;
	    d = Math.floor(d/16);
	    return (c=='x' ? r : (r&0x3|0x8)).toString(16);
	  });
	  return uuid;
	  };
	  
//在二维码上生成一个带uuid的随机数
var uuid=generateUUID();
var src=$.contextPath+"/servlet/QRImageServlet.servlet?code="+uuid+"";
$('#QRCode').attr('src',src);

最后二维码在页面中生成好了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值