总结之两种方式生成二维码(前端和后端生成)

后端方法

通过com.google.zxing生成二维码
1、引入依赖

<com.google.zxing>3.1.0</com.google.zxing>
<!--二维码-->
			<dependency>
				<groupId>com.google.zxing</groupId>
				<artifactId>core</artifactId>
				<version>${com.google.zxing}</version>
			</dependency>
			<dependency>
				<groupId>com.google.zxing</groupId>
				<artifactId>javase</artifactId>
				<version>${com.google.zxing}</version>
			</dependency>

使用并设置属性

二维码字符串
public static String createQRCode(String content, int width, int height) throws IOException {

        String resultImage = "";
        if (!org.springframework.util.StringUtils.isEmpty(content)) {
            ServletOutputStream stream = null;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            @SuppressWarnings("rawtypes")
            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 指定二维码的纠错等级为中级
            hints.put(EncodeHintType.MARGIN, 1); // 设置图片的边距

            try {
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ImageIO.write(bufferedImage, "png", os);
                /**
                 * 原生转码前面没有 data:image/png;base64 这些字段,返回给前端是无法被解析,可以让前端加,也可以在下面加上
                 */
                resultImage = new String("data:image/png;base64," + Base64.encode(os.toByteArray()));

                return resultImage;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (stream != null) {
                    stream.flush();
                    stream.close();
                }
            }
        }
        return null;
    }

使用字符串

  String imgSrc = BarcodeUtil.createQRCode("1c990252effd4efa9fc69090805275d0",QRCODE_WIDTH,QRCODE_HEIGHT);
            qrCode.setImg("<img src=\""+imgSrc+"\" style=\"display: block;\" class=\"mCS_img_loaded\">");

二维码图片
/**
     * 生成二维码
     * @return
     * Description:
     * Date: 2017年7月3日
     * Time: 下午3:02:30
     * @author zeng.hanguang
     */
    public static String createORCode(String id){
        try{
            String content = id;
            /**
             * 获取根目录
             */
            String localDirPath = EnvFileUD.getUploadLocalDir()+File.separator+"code"+File.separator;
            /**
             * 文件id
             */
            String uuid = "6189723"+String.valueOf((int)((Math.random()*9+1)*100000))+String.valueOf((int)((Math.random()*9+1)*100000));
            /**
             * 文件保存路径
             */
            String dirPath=localDirPath+uuid+".gif";
            /**
             * 获取web服务器中的总目录名称
             */
            String rootDirPath = EnvFileUD.getUploadRootUrl()+File.separator+"code"+File.separator+uuid+".gif";
            //创建二维码对象
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

            //创建map
            Map<Object,Object> hints = new HashMap<Object,Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //生成二维码
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 150, 150);
            File outputFile = new File(dirPath);
            if(!outputFile.exists()){
                /**
                 * 创建目录
                 */
                outputFile.mkdirs();
            }
            //输出到流
            MatrixToImageWriter.writeToFile(bitMatrix, "gif", outputFile);
            return rootDirPath;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return
     * @Description: 根据图片地址转换为base64编码字符串
     * @Author:
     * @CreateTime:
     */
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

前端

引入qrcode.js
在这里插入图片描述

<script src="${resource_static_js_url}/qrcode/qrcode.min.js"></script>
<div id="qrcode"></div>
<script type="text/javascript">
    new QRCode(document.getElementById("qrcode"), "${url}");  // 设置要生成二维码的链接
    var qrcode = new QRCode("test", {
        text: "${url}",
        width: 128,
        height: 128,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值