利用谷歌zxing生成二维码

1.在maven中添加谷歌zxing jar的依赖


com.google.zxing
core
3.0.0

 

com.google.zxing
javase
3.0.0

 

 

2.代码

package com.royalnu.origin.module.ori.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Value;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


public class QrCodeUtil {
	
	private static final String CHARSET = "utf-8";  
        private static final String FORMAT_NAME = "JPG";  
    
    /** 
     * 生成带二维码,并保存到磁盘 
     * @param content   源内容 
     * @param imgPath   生成二维码保存的路径 
     * @param needCompress  是否要压缩 
     * @param number  编号(以此命名图片) 
     * @return      boolean值
     * @throws Exception 
     */ 
    @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	public static Boolean createImage(String content, String imgPath,String number,Integer qrCodeSize,boolean needCompress) throws Exception {  
        Hashtable hints = new Hashtable();  
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);  
        hints.put(EncodeHintType.MARGIN, 1);  
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize,hints);  
        int width = bitMatrix.getWidth();  
        int height = bitMatrix.getHeight();  
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
        for (int x = 0; x < width; x++) {  
            for (int y = 0; y < height; y++) {  
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);  
            }  
        }  
        String fileName =number+ ".jpg";
        File file = new File(imgPath + "/" + fileName);
        if(!file.exists()){
            file.mkdirs();
        }
        return  ImageIO.write(image, FORMAT_NAME, file);   
    }  
  
 
//    public static void main(String[] args) throws Exception {  
//        
//    	QrCodeUtil util = new QrCodeUtil();
//          
//        //生成不带logo 的二维码  
//        String textt = "http://www.baidu.com";  
//        util.createImage(textt, "d:\\", "345", true);  
//          
//   
//    }  
	
}

 

参考资料:http://blog.csdn.net/wangnan537/article/details/50353174

                  http://tec.5lulu.com/detail/110d4n2ehcg9a857d.html

 

你可能感兴趣的:(java)