java生成二维码工具类
1,先引入谷歌的插件zxing的maven坐标
<!-- 二维码 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.1</version> </dependency>
2,然后复制下面的工具类,使用即可
package com.sport.sportactivityserver.common.utils; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import org.apache.commons.codec.binary.Base64; import java.io.ByteArrayOutputStream; import java.io.IOException; public class QRCodeGenerator { // 生成二维码高度 public static final int width = 350; // 生成二维码宽度 public static final int height = 350; /** * 生成二维码 * @param text 二维码内容 * @return 返回二维码的base64编码 */ public static String generateQRCodeImage(String text) { try { return generateQRCodeImage(text, width, height); } catch (WriterException | IOException e) { e.printStackTrace(); } return null; } /** * 生成二维码 * @param text 二维码内容 * @param width 二维码高度 * @param height 二维码宽度 * @return 返回二维码的base64编码 * @throws WriterException * @throws IOException */ private static String generateQRCodeImage(String text, int width, int height) throws WriterException, IOException { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream); byte[] imgByte = Base64.encodeBase64(outputStream.toByteArray()); return "data:image/png;base64," + new String(imgByte); } public static void main(String[] args) { try { String s = generateQRCodeImage("This is my first QR Code", 350, 350); System.out.println(s); } catch (WriterException e) { System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage()); } catch (IOException e) { System.out.println("Could not generate QR Code, IOException :: " + e.getMessage()); } } }
3,结果