java后端生成二维码

相信大家在做项目的时候,都会有这样的需求,利用二维码记录信息,那么我采用的是后台生成给前端进行展示

项目前端需要二维码,二维码的生成采用后台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));
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值