Java convert file to QR code

The main code for generating a two-dimensional code is in steps 1 and 2, and the following steps 3, 4, and 5 involve specific services. If you use this tool class, you need to copy the code of the first two steps.

1. Introduce third-party dependencies for generating QR codes into the project pom.xml file

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>

2. Tools for generating QR codes

/**
 * 二维码生成工具
 */
public class QRCodeUtils {
    
    

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 根据字符串生成对应的二维码图片png
     * 大小:300*300
     * <p>
     * content:要转换的文字内容
     * path:生成的二维码图片的绝对路径
     * filename: 生成后的二维码图片的文件名
     * Constants.SYS_HOME_QRCODE_FORMAT=“PNG”。我在外部常量类中定义的一个常量,即生成的二维码图片的格式
     */
    public static void buildQuickMark(String content, String path, String filename) {
    
    
        try {
    
    
            BitMatrix byteMatrix = new MultiFormatWriter().encode(new String(content.getBytes(), "iso-8859-1"),
                    BarcodeFormat.QR_CODE, 300, 300);
            String format = Constants.SYS_HOME_QRCODE_FORMAT;
            File file = new File(path + "\\" + filename + "." + format);
            BufferedImage image = toBufferedImage(byteMatrix);
            if (!ImageIO.write(image, format, file)) {
    
    
                throw new IOException("Could not write an image of format " + format + " to " + file);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 设置二维码格式
     *
     * @param matrix
     * @return
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
    
    
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
    
    
            for (int y = 0; y < height; y++) {
    
    
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
}


//测试将http://127.0.0.1:8888链接生成二维码
public static void main(String[] args) {
    
    
    //设置图片内容
    String content = "http://127.0.0.1:8888";
    //设置图片存放位置
    String path = "D:\\QRCode";
    //设置生成的图片的名字
    String filename = "test";
    QRCodeUtils.buildQuickMark(content, path, filename);
    System.out.println("创建成功");
}

3. The generated QR code image

insert image description here

4. The business layer code implementation class for generating the QR code

/**
 * 二维码 业务层处理
 *
 * @author sense
 */
@Service
public class SysQRCodeServiceImpl implements SysQRCodeService {
    
    

    @Autowired
    SysConfigService sysConfigService;

    public String getQRCode() {
    
    
        return saveQRCode();
    }

    //将生成的二维码保存到服务器,并返回文件名
    public String saveQRCode(){
    
    
        //首先拿到系统配置中的要转换的二维码的值
        String configValue = sysConfigService.selectConfigByKey(Constants.SYS_HOME_QRCODE).getConfigValue();
        String qrCodeName = "QRCode";
        //生成二维码图片
        QRCodeUtils.buildQuickMark(configValue,uploadUrl(), qrCodeName);
        String resultQRCodeName = qrCodeName+"."+Constants.SYS_HOME_QRCODE_FORMAT;
        return resultQRCodeName;
    }


    //设置生成的二维码存放路径
    public String uploadUrl() {
    
    
        // 根据系统当前日期
        Date now = new Date();
        String date = new SimpleDateFormat("yyyyMM").format(now);
        // 设置图片存放地址
        String uploadFilePath = SenseConfig.getUploadFilePath();
        // 判断是否存在地址,如果不存在,按照规则创建文件夹
        File addr = new File(uploadFilePath);
        if (!addr.exists()) {
    
    
            addr.mkdirs();
        }
        return uploadFilePath;
    }

5. Business layer code interface for generating QR code

public interface SysQRCodeService {
    
    
    String getQRCode();
}

6. The interface for generating the QR code is called by the front-end to obtain the image name of the generated QR code

/**
 * QRCode 生成二维码
 */
@RestController
@RequestMapping("/sys/QRCode")
public class SysQRCodeController {
    
    

    @Autowired
    SysQRCodeService sysQRCodeService;

    @RequestMapping()
    public AjaxResult getQRCode(){
    
    
        return AjaxResult.success(sysQRCodeService.getQRCode());
    }
}

Guess you like

Origin blog.csdn.net/qq_46112274/article/details/124443866
Recommended