专栏名称: Java大后端
专注分享Java后端技术,包括Spring Boot、Spring Cloud、MyBatis、MySQL、Dubbo、Zookeeper、ES、K8S、Docker、Redis、MQ、分布式、微服务等主流后端技术。
目录
相关文章推荐
Foodaily每日食品  ·  配角掀桌,从默默无闻到霸占C位:卖疯了的坚果 ... ·  2 天前  
艾格吃饱了  ·  有时候觉得上班也挺好的。。。 ·  4 天前  
每天学点做饭技巧  ·  可媲美大牌的平价冲牙器,360度全方位清洁口 ... ·  4 天前  
51好读  ›  专栏  ›  Java大后端

SpringBoot 生成二维码,你知道怎么搞?

Java大后端  · 公众号  ·  · 2020-12-24 11:30

正文

效果图

步骤

maven依赖


        
            com.google.zxing
            javase
            3.3.0
        


工具类

package com.bennyrhys.mall.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/**
 * 描述:     生成二维码工具
 */
public class QRCodeGenerator {


    public static void generateQRCodeImage(String text, int width, int height, String filePath)
            throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    public static void main(String[] args) {
        try {
            generateQRCodeImage("Hello World", 350, 350, "E:/JAVA/mall/src/main/resources/images/QRTest.png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



service

   /**
     * 生成二维码
     * 图片可解析出访问的支付对应订单号的支付连接
     * @param orderNo 订单号
     * @return 返回图片地址
     */
    @Override
    public String qrcode(String orderNo) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String address = ip + ":" + request.getLocalPort();
        String payUrl = "http://" + address + "/pay?orderNo=" + orderNo;
        try {
            QRCodeGenerator.generateQRCodeImage(payUrl, 350, 350, Constant.FILE_UPLOAD_PATH + orderNo + ".png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String pngAddress = "http://" + address + "/images-dev/" + orderNo + ".png";
        return pngAddress;
    }


扩展

局域网调试

线上调试


切换ip

# 指定IP(防止ip转发获取的是内网ip) file.upload.ip=127.0.0.1


原文:

blog.csdn.net/weixin_43469680/article/details/110791319


(完)


最近热文:
分享一份Java架构师学习资料!
delete后加 limit是个好习惯么?
8年开发,连登陆接口都写这么烂...






请到「今天看啥」查看全文