0
点赞
收藏
分享

微信扫一扫

Java后端生成二维码(QrCode)

時小白 2022-04-04 阅读 37
java后端
  • 引入依赖
  <!-- 生成二维码所需依赖 -->
 <dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
  </dependency>
  <dependency>
     <groupId>com.github.liuyueyi.media</groupId>
     <artifactId>qrcode-plugin</artifactId>
     <version>2.5.2</version>
  </dependency>
  • 后端工具类开发
package com.example.util;

import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeOptions;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.awt.*;
import java.io.InputStream;

public class QrCodeUtil {
    /**
     * 生成普通二维码
     */
    public static String normal(String text) throws Exception {
        return QrCodeGenWrapper.of(text).asString();
    }

    /**
     * 生成带颜色的二维码
     */
    public static String color(String text) throws Exception {
        return QrCodeGenWrapper.of(text)
                .setDrawPreColor(Color.BLUE) // 蓝色二维码
                .asString();
    }

    /**
     * 生成带背景图片的二维码
     */
    public static String bg(String text, InputStream bgFile) throws Exception {
        return QrCodeGenWrapper.of(text)
                .setBgImg(bgFile)
                .setBgStyle(QrCodeOptions.BgImgStyle.PENETRATE)
                .setBgH(500)
                .setBgW(500)
                .setW(500)
                .setH(500)
                .asString();
    }

    /**
     * 生成图片填充二维码
     */
    public static String fill(String text, InputStream bgFile) throws Exception {
        return QrCodeGenWrapper.of(text)
                .setW(500)
                .setH(500)
                .setDrawEnableScale(true)
                .setErrorCorrection(ErrorCorrectionLevel.H)
                .setDrawStyle(QrCodeOptions.DrawStyle.IMAGE)
                .addImg(1, 1, bgFile)
                .asString();
    }

    /**
     * 生成gif二维码
     */
    public static String gif(String text, InputStream bgFile) throws Exception {
        return QrCodeGenWrapper.of(text)
                .setW(500)
                .setH(500)
                .setBgImg(bgFile)
                .setBgOpacity(0.5f)
                .setPicType("gif")
                .asString();
    }

    /**
     * 生成特殊形状二维码
     */
    public static String style(String text, InputStream bgFile) throws Exception {
        return QrCodeGenWrapper.of(text)
                .setBgH(500)
                .setBgW(500)
                .setW(500)
                .setH(500)
                .setDrawEnableScale(true)
                .setDrawStyle(QrCodeOptions.DrawStyle.CIRCLE)
                .asString();
    }

}

  • 前端请求代码省略(data是调用工具类返回的base64码)`
 // 前端解析方式大概如下:
$("#view_photo").attr("src","data:image/jpeg;base64,"+data);`
举报

相关推荐

0 条评论