使用谷歌zxing 生成二维码

package com.hkb.soulaud.pojo;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author lime
 * @Description 二维码
 * @Date 17:53 2020/4/3
 * @Modified by
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class QrImage implements Serializable {
    public static final int WIDTH = 300;
    public static final int HEIGHT = 300;
    /**
     * 文件夹路径
     */
    private String folderPath;
    /**
     * 文件全名
     */
    private String fileName;
    /**
     * 跳转链接
     */
    private String link;
    /**
     * 图片格式
     */
    private String format;

}

package com.hkb.soulaud.tools;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hkb.soulaud.pojo.QrImage;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Path;
import java.util.Hashtable;

/**
 * @author lime
 * @Description 二维码工具  使用谷歌zxing生成
 * @Date 9:54 2020/3/30
 * @Modified by
 */
@Slf4j
public class Qr {
    /**
     * 将二位码写入到目录
     *
     * @param image 二维码图片属性
     */
    public static void writeQrImage(QrImage image) throws WriterException, IOException {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        // 构造二维字节矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(image.getLink(), BarcodeFormat.QR_CODE, QrImage.WIDTH, QrImage.HEIGHT, hints);
        // 构造文件目录,若目录不存在,则创建目录
        final String filePath = image.getFolderPath() + image.getFileName();
        File folderFile = new File(image.getFolderPath());
        if (folderFile.exists() || folderFile.mkdirs()) {
            Path file = new File(filePath).toPath();
            // 将二位字节矩阵按照指定图片格式,写入指定文件目录,生成二维码图片
            MatrixToImageWriter.writeToPath(bitMatrix, image.getFormat(), file);
        }


    }

    /**
     * 获取二维码输入流
     *
     * @param content   内容
     * @param width     宽度
     * @param picFormat 图片格式
     * @return 输入流
     * @throws IOException     io异常
     * @throws WriterException 写入异常
     */
    public static InputStream getQrInputStream(String content, int width, String picFormat) throws IOException, WriterException {
        return new ByteArrayInputStream(getQrByte(content, width, picFormat));
    }

    /**
     * 生成二维码图片字节流
     *
     * @param content   二维码内容
     * @param width     二维码宽度和高度
     * @param picFormat 二维码图片格式
     */
    public static byte[] getQrByte(String content, int width, String picFormat) throws WriterException, IOException {
        // 构造二维字节矩阵,将二位字节矩阵渲染为二维缓存图片
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, width);
        BufferedImage image = toBufferedImage(bitMatrix);
        // 定义输出流,将二维缓存图片写到指定输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, picFormat, out);
        // 将输出流转换为字节数组
        return out.toByteArray();
    }

    /**
     * 将二维字节矩阵渲染为二维缓存图片
     *
     * @param matrix 二维字节矩阵
     * @return 二维缓存图片
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        int onColor = 0xFF000000;
        int offColor = 0xFFFFFFFF;
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor);
            }
        }
        return image;
    }

    /**
     * 解析二维码内容
     *
     * @param filepath 二维码路径
     */
    public static void readQr(String filepath) throws IOException, NotFoundException {
        MultiFormatReader multiFormatReader = new MultiFormatReader();
        File file = new File(filepath);
        // 图片缓冲
        BufferedImage image = null;
        // 二进制比特图
        BinaryBitmap binaryBitmap = null;
        // 二维码结果
        Result result = null;
        image = ImageIO.read(file);
        binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        result = multiFormatReader.decode(binaryBitmap);
        log.debug("读取二维码: {}", result.toString());
        log.debug("二维码格式: {}", result.getBarcodeFormat());
        log.debug("二维码内容: {}", result.getText());
    }

    public static void main(String[] args) throws IOException, WriterException {
        log.debug(OssFileTools.upload(getQrInputStream("aaa", 100, "png"), "aa.jpg"));
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等一场春雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值