java生成二维码的代码(使用谷歌zxing)

时间:2022-11-17 07:30:21
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;


import javax.imageio.ImageIO;


import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
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.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jwell.mms.common.api.BufferedImageLuminanceSource;


/**
 * 
 * @FileName:    二维码生成工具
 * @Company:     成都积微物联电子商务有限公司
 *
 * @author:      wolf
 * @version      V1.0
 * @date:        2016年12月16日 下午3:51:23
 * 
 * @Description: TODO
 *
 */
public class QRCodeUtil {


private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 180;

// LOGO宽度
private static final int WIDTH = 30;
// LOGO高度
private static final int HEIGHT = 30;

/**

* @param content
* @param needCompress
* @return
* @throws Exception
* @author wolf
* @date 2016年12月17日
*/
//参生的二维码无边框
private static BufferedImage createImageNoBorder(String content, 
boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);//控制边框大小

//去掉边框begin
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
//1.1去白边
int kongBai=10;//控制边框大小必须大于0
int[] rec = bitMatrix.getEnclosingRectangle();
int resWidth = rec[2] ;  
int resHeight = rec[3] ;  
BitMatrix resMatrix = new BitMatrix(resWidth+kongBai, resHeight+kongBai);  
resMatrix.clear();  
for (int i = 0; i < resWidth; i++) {  
   for (int j = 0; j < resHeight; j++) {  
       if (bitMatrix.get(i + rec[0], j + rec[1])) { 
            resMatrix.set(i+kongBai/2, j+kongBai/2); 
       } 
   }  
}  
//2
int qSOtherW = resMatrix.getWidth();
int qSOtherH = resMatrix.getHeight();
BufferedImage image = new BufferedImage(qSOtherW, qSOtherH,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < qSOtherW; x++) {
for (int y = 0; y < qSOtherH; y++) {
image.setRGB(x, y, resMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}

// 插入图片
QRCodeUtil.insertImageOther(image,qSOtherW,qSOtherH,needCompress);
//去掉边框end 

return image;
}


/**
* 插入LOGO,去掉边框

* @param source
*            二维码图片
* @param imgPath
*            LOGO图片地址
* @param needCompress
*            是否压缩
* @throws Exception
* @author wolf
* @date 2016年11月17日
*/
private static void insertImageOther(BufferedImage source, int qSOtherW,int qSOtherH,
boolean needCompress) throws Exception {


Image src = ImageIO.read(QRCodeUtil.class.getResourceAsStream("/logo.jpg"));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (qSOtherW - width) / 2;
int y = (qSOtherH - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}


/**
* 生成二维码(内嵌LOGO)

* @param content
*            内容
* @param imgPath
*            LOGO地址
* @param destPath
*            存放目录
* @param needCompress
*            是否压缩LOGO
* @throws Exception
* @author wolf
* @date 2016年11月17日
*/
private static void encode(String content, String destPath,String fileName,
boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImageNoBorder(content,
needCompress);
mkdirs(destPath);


String file = fileName+".jpg";
String pathFile=destPath+"/"+file;
deleteFile(pathFile);
ImageIO.write(image, FORMAT_NAME, new File(pathFile));
}




/**

*@param destPath 存放目录
* @author wolf
* @date 2016年11月17日
*@Description: 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);    
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}

/**

* @param fileName
* @author wolf
* @date 2016年11月17日
*@Description: 删除已有文件
*/
public static void deleteFile(String fileName) {
File file=new File(fileName);
if (file.exists()&&file.isFile()) {
file.delete();
}
}

/**

* @param fileName
* @author wolf
* @date 2016年11月17日
*@Description: 删除所有文件
*/
public static void delete(File file) {
if (!file.exists()) {
return;// 文件不存在,返回
}
File[] ff = file.listFiles();
for (File __f : ff) {
if (__f.isDirectory()) {//检查是否是一个文件夹
delete(__f);
}
__f.delete();
}
}


/**
* (打印标签)生成二维码(内嵌LOGO)

* @param content(json串)
*            内容
* @param imgPath
*            LOGO地址
* @param destPath
*            存储地址
* @fileName 生成二位码图片的名字
* @throws Exception
* @author wolf
* @date 2016年11月17日
*/
public static void encode(String content,String destPath,String fileName)throws Exception {
QRCodeUtil.encode(content, destPath,fileName, true);
}


/**
* 生成二维码(内嵌LOGO)

* @param content
*            内容
* @param imgPath
*            LOGO地址
* @param output
*            输出流
* @param needCompress
*            是否压缩LOGO
* @throws Exception
* @author wolf
* @date 2016年11月17日
*/
private static void encode(String content,OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImageNoBorder(content,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}


/**
* 生成二维码

* @param content
*            内容
* @param output
*            输出流
* @throws Exception
* @author wolf
* @date 2016年11月17日
*/
public static void encode(String content, OutputStream output)throws Exception {
QRCodeUtil.encode(content,output, true);
}


/**
* 解析二维码

* @param file
*            二维码图片
* @return
* @throws Exceptio
* @author wolf
* @date 2016年11月17日
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
LuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}


/**
* 解析二维码

* @param path
*            二维码图片地址
* @return
* @throws Exception
* @author wolf
* @date 2016年11月17日
*/
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}


public static void main(String[] args) throws Exception {
//Json
JSONObject jsonSave=new JSONObject();
//材料二维码
String fileName="TD20161202004";

/*jsonSave.put("matItemNo","物料编码");
jsonSave.put("matItemName","物料名称");
jsonSave.put("matNo","材料号");
jsonSave.put("matName","材料名称");
jsonSave.put("batchNumber","批次号");
jsonSave.put("matNum", "");
jsonSave.put("matWeight", "");*/

/*jsonSave.put("matItemNo","TBF-0025ISX");
jsonSave.put("matItemName","钛白粉ISX");
jsonSave.put("matNo","161202ISX");
jsonSave.put("matName","钛白粉ISX");
jsonSave.put("batchNumber","161202ISX");
jsonSave.put("matNum", "");
jsonSave.put("matWeight", "");*/

//货位二维码
/*jsonSave.put("storeName", "6号区");
jsonSave.put("locationName", "A-06");*/


//提单二维码
jsonSave.put("billNo", "TD20161202004");
jsonSave.put("planBillDate", "20161202");
jsonSave.put("carNo", "云A352G45X");
jsonSave.put("billCusName", "重庆市北碚灯塔包装");
jsonSave.put("remarks", "司机身份证号:5192813092736244");



//保存路径
String path="/barcode";
path=System.getProperty("java.class.path").substring(0, 2)+path;
System.out.println(path);

//生成二维码
String text = jsonSave.toString();
QRCodeUtil.encode(text,path,fileName);

//解析二维码
//String open=QRCodeUtil.decode(path+"/TD20161202004.jpg");

   //JSONObject jsonOpen=JSONObject.parseObject(open);

//System.out.println("姓名:"+jsonOpen.getString("name")+"   年龄:"+jsonOpen.getString("age"));
   //System.out.println(jsonOpen.toString());

}

}