pom文件
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
package com.cn.core.util;
import com.cn.core.common.Constant;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
/**
* 二维码生成工具类
* add by dhy
*/
public class ErCodeUtil {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
/**
* 根据字符串生成对应的二维码图片png
* 大小:200*200
* <p>
* content:要转换的内容
* path:生成的二维码图片的绝对路径
* filename: 生成的文件名
*/
public static void buildQuickMark(String content, String filename) {
try {
String path = Constant.PIC_URL;
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix byteMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, 200, 200, hints); //电子卡尺寸
String format = "png";
File file = new File(path + filename + "." + format);
BufferedImage image = toBufferedImage(byteMatrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static void buildQuickMarkToBaoZong(String content, String filename) {
try {
String path = Constant.PIC_URL;
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix byteMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, 300, 300, hints); //包总的尺寸
String format = "png";
File file = new File(path + filename + "." + format);
BufferedImage image = toBufferedImage(byteMatrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String content = "Http://www.baidu.com";
String filename = "test";
buildQuickMark(content, filename);
}
}