使用Google Zxing生成二维码&解析二维码

使用Google Zxing生成二维码&解析二维码

今天因为有生成与解析一些二维码的需求,所以就在网上找了一些相关的资料。

发现大部分人还是推荐Google 的Zxing,不过大家都生成文件存起来了。因为条件有限,公司没有文件服务器,所以就将图片转为BASE64存在数据库了。这边就分享一下相关的使用。

首先,你可以去官网下载它的jar包或者从Maven仓库中导入它。

jar包:https://repo1.maven.org/maven2/com/google/zxing/core/3.4.0/core-3.4.0.jar

Maven导入:

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

导入包之后,就可以正常使用了。

首先我们先写一些基础方法

将图片缓存转为字节数组:


    /**
     * 图片缓存转字节数组
     * @param bImage
     * @param format
     * @return
     */
    private static byte[] imageToBytes(BufferedImage bImage, String format) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, format, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

将bit矩阵转为图片缓存

    /**
     * 将bit矩阵转化为图片缓存
     * @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;
    }

图片缓存转图片解析结果:


    /**
     * 图片缓存转图片解析结果
     * @param bufferedImage
     * @return
     */
    private static Result getResultByBufferedImage(BufferedImage bufferedImage) {
        if (bufferedImage == null) {
            return null;
        }
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();
        hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

之后我们就可以愉快地写代码啦

首先实现生成二维码的BASE64编码的方法:


    /**
     * 生成二维码并使用Base64编码
     * @param content
     * @throws Exception
     */
    public static String getBase64QRCode(String content)  {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        //设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN,1);
        //设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置二维码的字符编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //画二维码
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        BufferedImage image = toBufferedImage(bitMatrix);
        //注意此处拿到字节数据
        byte[] bytes =imageToBytes(image,"jpg");
        //Base64编码
        String base64String = BASE64HEAD +Base64.getEncoder().encodeToString(bytes);
        return base64String;
    }

之后是它的逆过程,将base64编码的图片转为二维码对应的文本内容:


    /**
     * 将Base64的二维码转为文本
     * @param base64
     * @throws Exception
     */
    public static String getContentFromBase64(String base64)  {
        if (base64 == null) {
            return null;
        }

        // 如果传入数据带有BASE64文件的开头,则将其去掉
        if (base64.startsWith(BASE64HEAD)) {
            base64 = base64.substring(BASE64HEAD.length());
        }

        BufferedImage bufferedImage = null;
        try {
            byte[] base64bytes = new BASE64Decoder().decodeBuffer(base64.trim());
            bufferedImage = ImageIO.read(new ByteArrayInputStream(base64bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bufferedImage == null) {
            return null;
        }
        Result resultByBufferedImage = getResultByBufferedImage(bufferedImage);
        if (resultByBufferedImage == null) {
            return null;
        }
        return resultByBufferedImage.getText();
    }

以及将二维码图片对应的字节码转换为二维码中的文本信息:


    /**
     * 将二维码图片的字节码转为文本
     * @param imageBytes
     * @throws Exception
     */
    public static String getContentFromImage(byte[] imageBytes)  {
        if (imageBytes == null) {
            return null;
        }

        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bufferedImage == null) {
            return null;
        }
        Result resultByBufferedImage = getResultByBufferedImage(bufferedImage);
        if (resultByBufferedImage == null) {
            return null;
        }
        return resultByBufferedImage.getText();
    }

到这里,基本的功能就实现了。
如果有大佬有更好的实现方法,不胜赐教。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值