JAVA生成和解析二维码

目的:

通过谷歌的zxing工具生成支付宝和微信均可扫描的二维码。

步骤:

1 添加maven依赖
地址: https://mvnrepository.com/artifact/com.google.zxing/core

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

2 编码实现二维码生成工具类
(1)工具类 QRCodeUtil

public class QRCodeUtil {

    private static Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);
    public static final String CHARSET = "utf-8";
    public static final String FORMAT_NAME = "png";
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;

    public static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable 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) ? BLACK : WHITE);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            logger.error("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            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();
    }

    public static void encode(String content, String imgPath, String destPath, boolean needCompress)  {
        BufferedImage image = null;
        try {
            image = QRCodeUtil.createImage(content, imgPath, needCompress);
            logger.info("图片为:"+image);
            mkdirs(destPath);
            ImageIO.write(image, FORMAT_NAME, new File(destPath));
        } catch (Exception e) {
            logger.error("创建二维码失败:{}",e);
        }

    }

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

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

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

    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 hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

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


    public static void main(String[] args) throws Exception {
        // 存放在二维码中的内容
        String text = "https://me.csdn.net/DJLDYHZSZ";
        // 嵌入二维码的图片路径
        String filePath = QRCodeUtil.class.getClass().getResource("/").getPath();
        System.out.println(filePath.substring(1,filePath.length()));
        String imgPath = filePath+"META-INF/resources/images/background.jpg";
        // 生成的二维码的路径及名称
        String destPath = filePath.substring(1,filePath.length())+"META-INF/resources/images/QRCode.png";
        //生成二维码
        QRCodeUtil.encode(text, imgPath, destPath, true);
        // 解析二维码
        String str = QRCodeUtil.decode(destPath);
        // 打印出解析出的内容
        System.out.println(str);
    }
}

(2)工具类BufferedImageLuminanceSource

作用:这个类层次的目的是抽象在不同平台上的位图,实现成一个标准的接口用于请求灰度的亮度值。

public class BufferedImageLuminanceSource extends LuminanceSource {
private final BufferedImage image;
private final int left;
private final int top;
private static final int black = 0xFF000000;
private static final int white = 0xFFFFFFFF;

public BufferedImageLuminanceSource(BufferedImage image) {
    this(image, 0, 0, image.getWidth(), image.getHeight());
}

public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
    super(width, height);

    int sourceWidth = image.getWidth();
    int sourceHeight = image.getHeight();
    if (left + width > sourceWidth || top + height > sourceHeight) {
        throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
    }

    for (int y = top; y < top + height; y++) {
        for (int x = left; x < left + width; x++) {
            if ((image.getRGB(x, y) & black) == 0) {
                image.setRGB(x, y, white);
            }
        }
    }

    this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
    this.image.getGraphics().drawImage(image, 0, 0, null);
    this.left = left;
    this.top = top;
}

@Override
public byte[] getRow(int y, byte[] row) {
    if (y < 0 || y >= getHeight()) {
        throw new IllegalArgumentException("Requested row is outside the image: " + y);
    }
    int width = getWidth();
    if (row == null || row.length < width) {
        row = new byte[width];
    }
    image.getRaster().getDataElements(left, top + y, width, 1, row);
    return row;
}

@Override
public byte[] getMatrix() {
    int width = getWidth();
    int height = getHeight();
    int area = width * height;
    byte[] matrix = new byte[area];
    image.getRaster().getDataElements(left, top, width, height, matrix);
    return matrix;
}

@Override
public boolean isCropSupported() {
    return true;
}

@Override
public LuminanceSource crop(int left, int top, int width, int height) {
    return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
}

@Override
public boolean isRotateSupported() {
    return true;
}

@Override
public LuminanceSource rotateCounterClockwise() {
    int sourceWidth = image.getWidth();
    int sourceHeight = image.getHeight();
    AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
    BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
    Graphics2D g = rotatedImage.createGraphics();
    g.drawImage(image, transform, null);
    g.dispose();
    int width = getWidth();
    return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
}

}

3 将二维码展示给前端

@RestController
@RequestMapping("/auth/qrCode/*")
public class QRCodeController {
    private static Logger logger = LoggerFactory.getLogger(QRCodeController.class);

    /**
     *  生成不带背景图片的二维码
     * @param context
     * @param response
     */

    @GetMapping("getQRCode.htm")
    public void getQRCode(@RequestParam String context, HttpServletResponse response)  {
        String filename = "QRCode.png";
        try {
            //BufferedImage 转 InputStream
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageOutputStream imageOutput = null;
            if (StringUtils.isEmpty(context)){
                throw new ValidateException("二维码内容不为空");
            }
            BufferedImage image = QRCodeUtil.createImage(context, null, Boolean.TRUE);
            imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
            ImageIO.write(image, "png", imageOutput);
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            long length = imageOutput.length();
            response.setContentType("application/x-msdownload");
            response.setContentLength((int)length);
            response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes(QRCodeUtil.CHARSET),"iso-8859-1"));
            //输出流
            byte[] bytes = new byte[1024];
            OutputStream outputStream = response.getOutputStream();
            long count = 0;
            while(count < length){
                int len = inputStream.read(bytes, 0, 1024);
                count +=len;
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            logger.error("创建二维码失败:{}",e);
        }

  }

    /**
     *  生成带背景图片的二维码  ——暂时不用
     * @param context
     * @param response
     */
    @GetMapping("getQRCodeByBackgroundImag.htm")
    public void getQRCodeByBackgroundImag(String context,HttpServletResponse response) {
        String filename = "QRCode.png";
        try {
            //BufferedImage 转 InputStream
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
            Resource resource = SpringContextHolder.getApplicationContext().getResource("classpath:");
            File file = resource.getFile();
            BufferedImage backgroundImage = QRCodeUtil.createImage("https://blog.csdn.net/static_coder/article/details/78972800", file.getPath() + "/META-INF/resources/images/background.jpg", Boolean.TRUE);
            String destPath = file.getPath() + "/META-INF/resources/images/dest.png";
            QRCodeUtil.mkdirs(destPath);
            ImageIO.write(backgroundImage, QRCodeUtil.FORMAT_NAME, new File(destPath));
            // 生成二维码
            BufferedImage destImage =ImageIO.read(new File(destPath));
            ImageIO.write(destImage, "png", imageOutput);
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            long length = imageOutput.length();
            response.setContentType("application/x-msdownload");
            response.setContentLength((int)length);
            response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("gbk"),"iso-8859-1"));
            //输出流
            byte[] bytes = new byte[1024];
            OutputStream outputStream = response.getOutputStream();
            long count = 0;
            while(count < length){
                int len = inputStream.read(bytes, 0, 1024);
                count +=len;
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            logger.error("创建二维码失败:{}", e);
        }
    }
}

4 浏览器中展示:

在浏览器中输入地址 :https://项目域名/auth/qrCode/getQRCode.htm?context=https://me.csdn.net/DJLDYHZSZ
其中context指的的微信或支付宝扫描二维码后进入的网址。
展示二维码如下:

在这里插入图片描述
扫描二维码,即可进入我的博客。

注意:如果想生成带背景图片的二维码,只需要在浏览器中请求Controller中的第二个方法即可。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值