Java如何生成二维码工具
直接上代码
/**
* @author wyy
* @version 1.0
* @date 2020/12/4 13:42
* 二维码描述方法
**/
public class QrCode {
/**
* 生成二维码的方法写入输出流
*
* @param text 内容
* @param width 宽度
* @param height 高度
* @param filePath 输出流
* @throws WriterException 异常
* @throws IOException 异常
* @author wyy
*/
public static void generateQRCodeImage(String content, int width, int height, OutputStream filePath) throws WriterException, IOException {
generateQRCode(content, width, height, filePath);
}
/**
* 生成二维码的方法直接输出
*
* @param text 内容
* @param width 宽度
* @param height 高度
* @param filePath 输出流
* @throws WriterException 异常
* @throws IOException 异常
* @author wyy
*/
public static void generateQRCodeImage(String content, int width, int height, String filePath) throws WriterException, IOException {
generateQRCode(content, width, height, filePath);
}
/**
* 生成二维码的方法写入直接输出
*
* @param text 内容
* @param width 宽度
* @param height 高度
* @param filePath 输出流
* @throws WriterException 异常
* @throws IOException 异常
*/
private static void generateQRCode(String content, int width, int height, String filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
/**
* 生成二维码的方法写入输出流
*
* @param text 内容
* @param width 宽度
* @param height 高度
* @param filePath 输出流
* @throws WriterException 异常
* @throws IOException 异常
*/
private static void generateQRCode(String content, int width, int height, OutputStream filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", filePath);
}
}
utils
/**
* @author wyy
* @version 1.0
* @date 2020/12/4 13:33
* 二维码生成工具
**/
public class QrCodeUtil {
/**
* 生成二维码的方法
*
* @param content 内容
* @param width 宽度
* @param height 高度
* @param outputStream 输出流
*/
public static void generateQRCodeImge(String content, int width, int height, OutputStream outputStream) throws IOException {
try {
QrCode.generateQRCodeImage(content, width, height, outputStream);
} catch (WriterException e) {
e.printStackTrace();
}
}
/**
* 生成二维码的方法
*
* @param content 内容
* @param width 宽度
* @param height 高度
* @param outputStream 输出流
*/
public static void generateQRCodeImge(String content, int width, int height, String outputStream) throws IOException {
try {
QrCode.generateQRCodeImage(content, width, height, outputStream);
} catch (WriterException e) {
e.printStackTrace();
}
}
}
演示代码
@Test
void contextLoads() throws IOException {
QrCodeUtil.generateQRCodeImge("www.chuyuan.ink",350,350,"D:\\work\\img\\MyBlogAddress.png");
}
结果 会自动跳转至博主的博客网址 如果是文本信息识别出来的就是文本信息