二维码的生成与解析

1.首先导入所需的jar包

        <!--二维码的生成与解析-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>

2.下面是二维码生成与解析的工具类,可以直接拿去用

package com.fn.modules.iot.common.utils.qrcode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * @ClassName: QRCodeUtil
 * @Author: lxh
 * @Description: 二维码生成与解析工具类
 * @Date: 2021/9/2 15:29
 */
public class QRCodeUtil {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;

    /**
     * 创建二维码图片
     * @param content /
     * @param imgPath /
     * @param needCompress /
     * @return java.awt.image.BufferedImage
     * @author lxh
     * @date 2021/9/22 17:41
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 插入二维码中间的图片
     * @param source /
     * @param imgPath /
     * @param needCompress /
     * @author lxh
     * @date 2021/9/22 17:42
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        // 压缩LOGO
        if (needCompress) {
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            // 绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码存到本地
     * @param content
     * @param imgPath
     * @param destPath
     * @param needCompress
     * @return void
     * @author lxh
     * @date 2021/9/13 16:03
     */
    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        //随机生成名字
//        String file = new Random().nextInt(99999999)+".jpg";
//        ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
        return QRCodeUtil.createImage(content, imgPath, needCompress);
    }

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static void encode(String content, String imgPath, String destPath) throws Exception {
        QRCodeUtil.encode(content, imgPath, destPath, false);
    }

    public static void encode(String content, String destPath) throws Exception {
        QRCodeUtil.encode(content, null, destPath, false);
    }

    /**
     * 在线生成二维码
     * @param content
     * @param imgPath
     * @param output
     * @param needCompress
     * @return void
     * @author lxh
     * @date 2021/9/13 16:02
     */
    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }

    /**
     * 解析二维码
     * @param file
     * @return java.lang.String
     * @author lxh
     * @date 2021/9/14 14:22
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        //优化精度
        hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        //复杂模式,开启PURE_BARCODE模式
        hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }

    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }

}

3.下面是我的实例,可以参考


package com.fn.modules.iot.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @website https://el-admin.vip
 * @description 服务接口
 * @author lxh
 * @date 2021-09-02
 **/
public interface AuthenticationDetailsService {

    /**
     * 在线生成二维码
     * @param request
     * @param response
     * @param deviceName
     * @throws  Exception
     * @author lxh
     * @date 2021/9/13 16:25
     */
    void qrCode(HttpServletRequest request, HttpServletResponse response, String deviceName) throws Exception;

    /**
     * 生成本地二维码
     * @param request
     * @param response
     * @param deviceName
     * @throws  Exception
     * @author lxh
     * @date 2021/9/22 18:14
     */
    void qrLocalCode(HttpServletRequest request, HttpServletResponse response, String deviceName) throws Exception;

    /**
     * 解析二维码
     * @param codeUrl 二维码的url地址
     * @return java.lang.String
     * @throws Exception
     * @author lxh
     * @date 2021/9/14 14:27
     */
    String deQrCode(String codeUrl) throws Exception;
}

package com.fn.modules.iot.service.impl;

import com.fn.modules.iot.common.utils.qrcode.QRCodeUtil;
import com.fn.modules.iot.service.AuthenticationDetailsService;
import com.fn.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;

/**
 * @author lxh
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-02
 **/
@Service
@RequiredArgsConstructor
public class AuthenticationDetailsServiceImpl implements AuthenticationDetailsService {

    private final StringEncryptor stringEncryptor;

    @Override
    public void qrCode(HttpServletRequest request, HttpServletResponse response, String deviceName) throws Exception {
        // 嵌入二维码的图片路径,在resources目录下
        String imgPath = ClassLoader.getSystemResource("image/image.jpg").getPath();
        //二维码的内容加密
        String encrypt = stringEncryptor.encrypt(deviceName);
        //生成二维码
        QRCodeUtil.encode(encrypt, imgPath, response.getOutputStream(), true);
    }

    @Override
    public void qrLocalCode(HttpServletRequest request, HttpServletResponse response, String deviceName) throws Exception {
        // 嵌入二维码的图片路径,在resources目录下
        String imgPath = ClassLoader.getSystemResource("image/image.jpg").getPath();
        //二维码的内容加密
        String encrypt = stringEncryptor.encrypt(deviceName);
        //本地生成二维码的路径以及名称
        String dePath = "D:/qrCode/qrCode.jpg";
        //生成二维码
        QRCodeUtil.encode(encrypt, imgPath, dePath, true);
    }

    @Override
    public String deQrCode(String codeUrl) throws Exception{
        //二维码的地址(将地址转为File文件)
        File file = getFile(codeUrl);
        // 解析二维码(图片中的内容进行解析)
        String decode = QRCodeUtil.decode(file);
        //解析完成之后将本地缓存文件删除
        file.deleteOnExit();
        //将内容进行解密
        return stringEncryptor.decrypt(decode);
    }

    /**
     * 将图片url转化成File
     * @param url
     * @return java.io.File
     * @author lxh
     * @date 2021/9/14 14:30
     */
    public static File getFile(String url) {
        File file = null;
        URL fileUrl;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            file = File.createTempFile("qrCode", ".jpg");
            //下载
            fileUrl = new URL(url);
            inputStream = fileUrl.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

}


package com.fn.modules.iot.rest;

import com.fn.annotation.AnonymousAccess;
import com.fn.annotation.Log;
import com.fn.modules.iot.service.AuthenticationDetailsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lxh
 * @website https://el-admin.vip
 * @date 2021-09-02
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "鉴权信息详情管理")
@RequestMapping("/api/authenticationDetails/")
public class AuthenticationDetailsController {

    private final AuthenticationDetailsService authenticationDetailsService;

    @Log("在线生成二维码")
    @ApiOperation("在线生成二维码")
    @GetMapping("qrCode")
    @AnonymousAccess
    public void qrCode(HttpServletRequest request, HttpServletResponse response, @RequestParam String deviceName) throws Exception {
        authenticationDetailsService.qrCode(request, response, deviceName);
    }

    @Log("生成本地二维码")
    @ApiOperation("在线生成二维码")
    @GetMapping("qrLocalCode")
    @AnonymousAccess
    public void qrLocalCode(HttpServletRequest request, HttpServletResponse response, @RequestParam String deviceName) throws Exception {
        authenticationDetailsService.qrLocalCode(request, response, deviceName);
    }

    @Log("解析二维码")
    @ApiOperation("解析二维码")
    @GetMapping("deQrCode")
    @AnonymousAccess
    public String deQrCode(@RequestParam String codeUrl) throws Exception {
        return authenticationDetailsService.deQrCode(codeUrl);
    }


}

这个是在线生成的图片
在这里插入图片描述
这个是本地生成的图片
在这里插入图片描述
这是解析后的结果
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值