先贴上二维码工具类的方法。
操作比较简单,将url生成对应的二维码,并且同时指定二维码大小。可以修改方法达到指定更多参数的效果。
public static BufferedImage createQRCode(String url, int size) {
// 生成二维码配置
Hashtable hints = new Hashtable();
// 编码、容错率、二维码边框宽度,
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN,10);
// 自定义白边边框宽度
int margin = 5;
BufferedImage bi = null;
try {
// 生成bitMatrix
BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, size, size, hints);
// 生成新的bitMatrix
bitMatrix = updateBit(bitMatrix, margin);
bi = MatrixToImageWriter.toBufferedImage(bitMatrix);
// 根据size放大、缩小生成的二维码
bi = zoomInImage(bi, size, size);
} catch (Exception e) {
throw new MyException("二维码获取失败");// 自定义异常
}
return bi;
}
private static BitMatrix updateBit(BitMatrix matrix, int margin){
int tempM = margin * 2;
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + tempM;
int resHeight = rec[3] + tempM;
// 按照自定义边框生成新的BitMatrix
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for(int i = 0; i < resWidth - margin; i++){
for(int j = margin; j < resHeight - margin; j++){
if(matrix.get(i-margin+rec[0],j-margin+rec[1])){
resMatrix.set(i,j);
}
}
}
return resMatrix;
}
public static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height){
BufferedImage bufferedImage = new BufferedImage(width, height, originalImage.getType());
Graphics graphics = bufferedImage.getGraphics();
graphics.drawImage(originalImage, 0, 0, width, height, null);
graphics.dispose();
return bufferedImage;
}
有了二维码之后想要放到图片里面去的话,可以使用ImageIO。
public static String updatePic() throws IOException {
BufferedImage qrCode = GenerateImgUtil.createQRCode("http://www.baidu.com", 150);
BufferedImage read ;
byte[] bytes;
// 获取一个输入流
File file = new File("");
FileInputStream fileInputStream = new FileInputStream(file);
read = ImageIO.read(fileInputStream);
Graphics2D graphics = read.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
// 二维码坐标
int width = read.getWidth();
int height = read.getHeight();
int x = 450;
int y = 350;
if((x+qrSize) > width || (y+qrSize) > height){
throw new MyException("请重新设定位置");
}
graphics.drawImage(qrCode, x, y, null);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(read, "png", byteArrayOutputStream);
bytes = byteArrayOutputStream.toByteArray();
// FileOutputStream fileOutputStream = new FileOutputStream(new File(""));
// fileOutputStream.write(bytes);
// fileOutputStream.close();
// 可以写入到文件,也可以直接返回
String s = Base64.getEncoder().encodeToString(bytes);
return s;
}