Java生成二维码
单元测试版:
导入jar包:
链接:https://pan.baidu.com/s/1qR4Mh0pwBAhpzx5gqCXDHg
提取码:a1qa
导入里面的zxing3.2.1.jar包
Java代码:
package ewm.test; import java.io.File; import java.nio.file.Path; import java.util.HashMap; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class Demo { public static void main(String[] args) { if (orCode("https://www.ak1ak1.com/catalog.html", "F:\\1.jpg")) { System.out.println("ok,成功"); } else { System.out.println("no,失败"); } } private static boolean orCode(String content, String path) { /* * 图片的宽度和高度 */ int width = 300; int height = 300; // 图片的格式 String format = "png"; // 二维码内容 // String content = "hello,word"; // 定义二维码的参数 HashMap hints = new HashMap(); // 定义字符集编码格式 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 纠错的等级 L > M > Q > H 纠错的能力越高可存储的越少,一般使用M hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 设置图片边距 hints.put(EncodeHintType.MARGIN, 2); try { // 最终生成 参数列表 (1.内容 2.格式 3.宽度 4.高度 5.二维码参数) BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); // 写入到本地 Path file = new File(path).toPath(); MatrixToImageWriter.writeToPath(bitMatrix, format, file); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }
web版本:
导入maven依赖
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> <scope>compile</scope> </dependency>
Java代码:
public void dowanload(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception { Project project = JSON.parseObject(JSONObject.toJSONString(getProject(id).getData(), true),Project.class); //二维码中包含的信息 String content = project.getPageUrl() + "&" + project.getProjectID(); Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); // 指定编码格式 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 指定纠错级别(L--7%,M--15%,Q--25%,H--30%) hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200, hints); //设置请求头 response.setHeader("Content-Type","application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + project.getProjectID() + ".png"); OutputStream outputStream = response.getOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream); outputStream.flush(); outputStream.close(); }