小程序动态生成二维码,生成image图片
前端:
<image src="{{img_usrl}}" style="width:100%;height:104px;" bindlongtap="saveImg"></image>
js部分:在onLoad中请求
//我的userid 值为:239a3c37-3c2e-4a9d-be74-557638b23b63
this.setData({ img_usrl: getApp().getBaseUrl() + "/icon/" + userid });
java后台:
@RequestMapping("icon/{cateogry}") public void getQrcodeImg(@PathVariable("cateogry") String cateogry, HttpServletRequest request, HttpServletResponse response){ try { //cateogry的值为前端请求的值:239a3c37-3c2e-4a9d-be74-557638b23b63 String url = "固定写死的url路径?id参数="+cateogry; BufferedImage image = QRCodeUtli.getqrcode(url); response.setContentType("image/png"); OutputStream stream = response.getOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "png", out); stream.write(out.toByteArray()); stream.flush(); stream.close(); } catch (Exception e) { e.printStackTrace(); } }
工具QRCodeUtli类:
package com.early.api.util; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; public class QRCodeUtli { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; public static BufferedImage getqrcode(String code) { int width = 400; // 图像宽度 int height = 400; // 图像高度 Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.MARGIN, 0);//设置白边宽度,取值0~4 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); try { BitMatrix bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.QR_CODE, width, height, hints); BufferedImage image = toBufferedImage(bitMatrix); return image; } catch (WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); } } return image; } }
pom文件需要引用的包:
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.1</version> </dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
时间,请带我像一条小溪流般,安静地流淌,汇入爱的海洋。