赞
踩
相信大家在做项目的时候,都会有这样的需求,利用二维码记录信息,那么我采用的是后台生成给前端进行展示
项目前端需要二维码,二维码的生成采用后台java生成,格式为base64
具体代码如下:
@ApiOperation("base64") @PostMapping("/qr_code") public Result<String> getQrCode() throws Exception{ WechatUser currentUser =wechatUserService.getCurrentUser(); if(currentUser==null){ throw new JwtTokenException("用户已下线,请重新登录"); } int BLACK = 0xFF000000; int WHITE = 0xFFFFFFFF; String text = wechatUtils.getDomain()+"/api/wx/recommond?userId=" + currentUser.getUserId(); // 设置编码,防止中文乱码 Hashtable<EncodeHintType, Object> ht = new Hashtable<EncodeHintType, Object>(); ht.put(EncodeHintType.CHARACTER_SET, "UTF-8"); int width = 400; int height = 400; // 设置二维码参数(编码内容,编码类型,图片宽度,图片高度,格式) BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, ht); int b_width = bitMatrix.getWidth(); int b_height = bitMatrix.getHeight(); // 建立图像缓冲器 BufferedImage image = new BufferedImage(b_width, b_height, BufferedImage.TYPE_3BYTE_BGR); for (int x = 0; x < b_width; x++) { for (int y = 0; y < b_height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); String format = "jpg"; ImageIO.write(image, format, out); // QrConfig qrConfig = QrConfig.create(); // BufferedImage generate = QrCodeUtil.generate(jsonObject.toJSONString(), qrConfig); // byte[] bytes = QrCodeUtil.generatePng(jsonObject.toJSONString(), width,height); byte[] bytes=out.toByteArray(); return Result.success(Base64.encode(bytes)); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。