[Java]利用google zxing生成QRCode二维码或Barcode条码,输出到文件或Spring中输出到网页

2021-02-06 1036点热度 0人点赞 0条评论

利用Google的zxing生成二维码或者条码非常简单,下面来介绍下

首先准备工作,加入依赖

如果是Maven,加入pom.xml:

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

如果是Gradle,加入build.gradle

compile "com.google.zxing:core:3.4.1"
下面生成二维码举例,可自定义颜色,详见代码注释
public static BufferedImage generateQRCode(String content) throws Exception {
    Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    hints.put(EncodeHintType.MARGIN, 2);
    //长宽如果要自定义,可以作为参数传进来
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 800, 800, hints);
    return toBufferedImage(bitMatrix);
}

private static BufferedImage toBufferedImage(BitMatrix matrix) {
    int black = 0xFF000000;//用于设置图案的颜色
    int white = 0xFFFFFFFF; //用于背景色
    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));
//              image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
        }
    }
    return image;
}

生成了BufferedImage,如果想要保存到文件,可以使用ImageIO.write(bufferedImage, "jpeg", new File("/Users/Terry/Downloads/a.jpg"));

如果要在Spring里作为web输出,可以在Controller里增加:

@RequestMapping(value = "/qrcode.jpg", method = RequestMethod.GET, headers = "Accept=image/*", produces = "image/jpg")
public void qrcode(@RequestParam(value = "content", required = true) String content, HttpServletResponse response) throws WriterException {
    BufferedImage bufferedImage = generateQRCode(content);
    //JDK版本较低的情况下,改用try catch
    try (ServletOutputStream outputStream = response.getOutputStream()) {
        ImageIO.write(bufferedImage, "jpeg", outputStream);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

如果需要在生成的二维码中间,加一个 logo,可以参考我的另一篇文章:https://blog.terrynow.com/2021/02/09/zxing-generate-qrcode-with-logo-in-center/

https://blog.terrynow.com/2021/02/09/zxing-generate-qrcode-with-logo-in-center/

下面生成条码举例,和二维码是类似的,这里就不多做说明了
//根据内容生成barcode条码
public BufferedImage barcode(String content) throws WriterException {
    Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    hints.put(EncodeHintType.MARGIN, 2);
    //长宽如果要自定义,可以作为参数传进来
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, 800, 400, hints);
    return toBufferedImage(bitMatrix);
}

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论