Java利用google.zxing生成和解析二维码

操作环境:jdk1.8、SpringBoot 2.5.4

编辑器:IDEA

依赖包:

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>

创建工具类:QRCodeImageUtil

public class QRCodeImageUtil {
    private static final int BLACK = 0XFF000000;
    private static final int WHITE = 0XFFFFFFFF;

    public static BufferedImage buildQuickMark(String content, String path, String filename) throws Exception {
        //content 要转换的字符内容
        //path 生成图片保存的路径
        //filename 生成图片文件名称
        try {
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //设置高容错率
            BitMatrix byteMatrix = new MultiFormatWriter().encode(new String(content.getBytes(), "ISO-8859-1"),
                    BarcodeFormat.QR_CODE, 200, 200,hints); //设置图片大小200*200,可用常量表示
            BufferedImage image = toBufferedImage(byteMatrix);
            return image;
            // 保存到本地
            //String format = "png";
            //File file = new File(path+"\\"+filename+"."+format);
            /*
            if (!ImageIO.write(image, format, file)) {
                throw new IOException("Could not write an image of format " + format + " to " + file);
            }
             */
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    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;
    }
}

Controller接收需要转换的字符串并返回给前端:

    @RequestMapping("/getQRCode")
    @ResponseBody
    public String getQRCode(@RequestParam("str") String str, HttpServletResponse response){
        //返回给前端页面展示
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            BufferedImage bufferedImage = QRCodeImageUtil.buildQuickMark(str,"C:\\Users\\wisdom21111\\Desktop","test");
            ImageIO.write(bufferedImage,"png",baos);
            byte[] bytes = baos.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            String png_base64 = encoder.encodeBuffer(bytes).trim();
            png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
            return png_base64;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回给前端下载
        /*
        OutputStream outputStream = null;
        try {
            BufferedImage bufferedImage = QRCodeImageUtil.buildQuickMark(str,"C:\\Users\\wisdom21111\\Desktop","test");
            response.setContentType("image/png");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            ImageIO.write(bufferedImage,"png",response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
         */
        return null;
    }

前端页面展示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>生成二维码</title>
</head>
<script src="./js/jquery-3.3.1.js"></script>
<body>
    <h1>输入字符串以生成二维码</h1>
    <form action="#" method="get" onsubmit="return generateQRCode();">
        <input type="text" id="str" name="str"/>
        <input type="submit" id="generate" value="生成"/>
        <button id="download">下载</button>
    </form>
    <img src="#" alt="二维码" id="qrcode">
</body>
<script>
    function generateQRCode(){
        console.log("生成二维码");
        $.ajax({
            type:'post',
            url:'/api/code/getQRCode',
            data:{
                "str":$("#str").val()
            },
            async:true,
            responseType:'blob',
            success:function(data){
                $("#qrcode").attr("src","data:image/png;base64,"+data);
            },
            error:function(data){
                console.log("error");
                console.log(data);
            }
        });
        return false;
    }
</script>
</html>

解析二维码图片:

        依赖包:

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.4.1</version>
        </dependency>

工具类解析方法:

        

    public static String decode(File file){
        try {
            MultiFormatReader formatReader = new MultiFormatReader();
            BufferedImage image = ImageIO.read(file);    //读取此文件识别成一个图片
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            //定义二维码参数
            HashMap hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    //定义内容字符集的编码

            Result result = formatReader.decode(binaryBitmap,hints);
//            System.out.println("解析结果:" + result.toString());
//            System.out.println("二维码格式类型:" + result.getBarcodeFormat());
//            System.out.println("二维码文本内容:" + result.getText());
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

Controller层调用:

        

    @PostMapping("/uploadImage")
    @ResponseBody
    public String uploadImage(@RequestParam("imageFile") MultipartFile multipartFile) throws IOException {
        System.out.println(multipartFile.getOriginalFilename());
        File file = null;
        file = File.createTempFile("temp",null);
        multipartFile.transferTo(file); //将multipartfile转换为file
        String text = QRCodeImageUtil.decode(file);
        file.deleteOnExit();
        System.out.println(text);
        return text;
    }

前端上传图片:

<form action="#" onsubmit="return uploadImage();" type="post">
        <input type="file" id="imageFile" name="imageFile"/>
        <input type="submit" value="上传"/>
    </form>
    <div>
        <p>上传图片解析后的内容:<span id="imageContent"></span></p>
    </div>
<script>
function uploadImage(){
        console.log("上传图片解析二维码");
        var formData = new FormData();
        try {
            formData.append("imageFile", $("#imageFile")[0].files[0]);
            $.ajax({
                url: "/api/code/uploadImage",
                type: 'post',
                data: formData,
                processData: false,
                contentType: false,
                cache:false,
                success: function (data) {
                    console.log("success");
                    $("#imageContent").html(data);
                },
                error: function (data) {
                    console.log("error");
                    console.log(data);
                }
            });
        }catch(Exception){
            console.log("ddd");
        }
        return false;
    }
</script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值