定义常量
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static final String CHARSET = "utf-8";
创建二维码方法
/**
* 创建二维码图片
* @param content 二维码内容
* @param width 宽度
* @param height 高度
* @return
* @throws Exception
*/
public static BufferedImage createImage(String content, int width, int height) 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, width, height,
hints);
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) ? BLACK : WHITE);
}
}
return image;
}