java生成二维码:
第一步创建一个Mavean工程(本文springboot+mavean)
创建mavean工程在这里就不多做介绍,默认大家都会
第二步导入mavea依赖:
<!--生成二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
第三步编写二维码生成工具类:
**
* oauth:xiaowang
* java生成二维码
* */
public class QrCodeUtils {
/**
* @param text 加密文本
* @param width 宽度
* @param height 高度
* @param filePath 文件输出目录
*这个是以文件的方式写入到本地磁盘
* */
public static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
/*
* @param condContent 加密文本
* @param width 宽度
* @param height 高度
* @param outputStream 响应输出流
*这个是以输出流的方式响应给浏览器
* */
public static void createCodeToOutputStream(String condContent,int with,int height,OutputStream outputStream){
if (condContent==null||"".equals(condContent.trim())){
return;
}
condContent=condContent.trim();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix encode = multiFormatWriter.encode(condContent, BarcodeFormat.QR_CODE,with,height);
MatrixToImageWriter.writeToStream(encode,"PNG",outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
//这里是输出到文件测试
public static void main(String[] args) {
String path="F:\\workspeck\\qrcode\\src\\main\\resources\\static\\1.png";
try {
generateQRCodeImage("hello",500,300,path);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
第四步编写控制层Controller:
@Controller
public class QrCodeController {
@ResponseBody
@RequestMapping(value = "/qrcode/{code}")
public void Qrcode(@PathVariable("code")String code, HttpServletRequest request, HttpServletResponse response){
try {
QrCode.createCodeToOutputStream(code,500,300,response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
第五步启动项目测试结果;
浏览器地址栏输入:http://localhost:8848/qrcode/xiaowang979578444
最终效果图如下: