Java--批量生成二维码并压缩成zip以IO流形式返回前端


前言

除了单个二维码图片的生成,还有批量导出的功能,具体就是根据选择生成的一批二维码图片先添加到一个zip压缩包中,然后将这个zip压缩包流返回给前端进行下载。
写博客的目的有两个:
1、作为笔记以后自己方便使用。
2、分享给大家借鉴,在实际去写时少走一些弯路。


一、使用技术

1、这里我们使用谷歌的zxing工具包进行二维码图片的生成,生成之后在这个图片的顶部加上我们需要的文字,当然文字的位置是可调的,也可以加在下面,代码都有。 2、添加到zip压缩包,然后使用流的方式将zip传输出去。

二、开发步骤

1.pom中引入zxing

代码如下:

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

2.二维码工具类的编写

代码如下:

package com.ampthon.func.api.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtils {

    /**
     * 黑色
     */
    private static final int BLACK = 0xFF000000;
    /**
     * 白色
     */
    private static final int WHITE = 0xFFFFFFFF;
    /**
     * 宽
     */
    private static final int WIDTH = 2000;
    /**
     * 高
     */
    private static final int HEIGHT = 2000;

    /**
     * 图片高度增加60
     */
    private static final int PIC_HEIGHT = HEIGHT + 120;

    /**
     * 二维码传图片
     *
     * @param matrix
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();

        BufferedImage image = new BufferedImage(width, PIC_HEIGHT, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < PIC_HEIGHT; y++) {
                image.setRGB(x, y, WHITE);
            }
        }
        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 content 扫描二维码的内容
     * @param format  图片格式 jpg
     *                文件
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static BufferedImage generateQrCode(String content, String format) throws Exception {

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        @SuppressWarnings("rawtypes")
        Map hints = new HashMap();
        // 设置UTF-8, 防止中文乱码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN, 5);
        // 设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 画二维码
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage image = toBufferedImage(bitMatrix);
        return image;
    }


    /**
     * 把生成的图片写到指定路径
     *
     * @param qrcFile       路径
     * @param qrCodeContent 二维码内容
     * @param pressText     增加的文字
     * @throws Exception
     */
    public static void generateQrCodeByPath(File qrcFile, String qrCodeContent, String pressText) throws Exception {


        BufferedImage image = generateQrCode(qrCodeContent, "jpg");

        Graphics g = image.getGraphics();
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //设置字体,大小
        Font font = new Font("黑体", Font.PLAIN, 150);
        g.setFont(font);
        g.setColor(Color.black);
        FontMetrics metrics = g.getFontMetrics(font);
        // 文字在图片中的坐标 这里设置在中间
        int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
        //  int startY=HEIGHT+(PIC_HEIGHT-HEIGHT)/2;  //文字在二维码上面
		int startY = PIC_HEIGHT - HEIGHT;  //文字在二维码下面
        g.drawString(pressText, startX, startY);

        g.dispose();
        image.flush();
        try {
            ImageIO.write(image, "jpg", qrcFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 把生成的图片返回到前端
     *
     * @param qrCodeContent 二维码内容
     * @param pressText     增加的文字
     * @throws Exception
     */
    public static BufferedImage generateQrCodeBack( String qrCodeContent, String pressText) throws Exception {


        BufferedImage image = generateQrCode(qrCodeContent, "jpg");

        Graphics g = image.getGraphics();
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //设置字体
        Font font = new Font("黑体", Font.PLAIN, 150);
        g.setFont(font);
        g.setColor(Color.black);
        FontMetrics metrics = g.getFontMetrics(font);
        // 文字在图片中的坐标 这里设置在中间
        int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
        //  int startY=HEIGHT+(PIC_HEIGHT-HEIGHT)/2;  //文字在二维码下面
		int startY = PIC_HEIGHT - HEIGHT;  //文字在二维码上面
        g.drawString(pressText, startX, startY);

        g.dispose();
        image.flush();
        return image;

    }


    /**
     * 生成二维码并使用Base64编码
     *
     * @param content 二维码内容
     * @return 返回base64图片
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static String getBase64QRCode(String content) throws Exception {


        String format = "png";

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        @SuppressWarnings("rawtypes")
        Map hints = new HashMap();

        // 设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN, 10);
        // 设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 画二维码
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);

        ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。
        ImageIO.write(image, format, os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。
        byte b[] = os.toByteArray();//从流中获取数据数组。
        String base64String = new BASE64Encoder().encode(b);

        // Base64编码
        return base64String;

    }
    

}



3.Controller的编写

代码如下:

package com.ampthon.controller;

import com.ampthon.func.api.impl.QRCodeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 二维码生成controller
 *
 * @author libin
 * @date 20210910
 */
@RestController
@RequestMapping("/api")
public class QRCodeController {

    //指定需要生成的二维码扫描出的地址
    public static final String url = "http://www.golden1994.top";
    

    /**
     *
     * @author lib
     * @date 20210909
     */
    @GetMapping("/addBatchQRCode")
    public String addBatchQRCode(HttpServletRequest request, HttpServletResponse response) {
        BufferedImage image = null;
        try {
            //这里可以先通过查库将需要生成的数据拼接到content中,然后作为二维码的标题
            String content = "mblog博客-您的理想之选";
            image = QRCodeUtils.generateQrCodeBack(url, content);
            ServletOutputStream os = response.getOutputStream();
            //由于我们只是测试,故只添加一个文件进去,实际情况需要遍历文件列表,然后逐一添加到压缩包流中。
            ZipOutputStream zo = new ZipOutputStream(os);
            ZipEntry zipEntry = new ZipEntry("mblog.jpg");
            zo.putNextEntry(zipEntry);
            zo.write(imageToBytes(image));
            zo.closeEntry();
            zo.flush();
            //关闭流
            zo.close();
            os.close();
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /**
     * 图片转字节数组
     *
     * @param bImg
     * @return
     */
    public static byte[] imageToBytes(BufferedImage bImg) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImg, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }


}

运行结果

启动服务后,在postman中访问该api接口:http://localhost:8080/api/addBatchQRCode
注意要选择Send and Download
在这里插入图片描述
会弹出下载框如下:
在这里插入图片描述下载后解压打开:
在这里插入图片描述

当然如果您需要把二维码文字生成在下方,可以找到这一行的注释打开,然后上面哪一行注释掉:

 //  int startY=HEIGHT+(PIC_HEIGHT-HEIGHT)/2;  //文字在二维码下面
		int startY = PIC_HEIGHT - HEIGHT;  //文字在二维码上面

效果如下:
在这里插入图片描述
喜欢的朋友欢迎一键三连。我们一起学习,进步~~

  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
要在 Java批量打印二维码,可以使用 Zebra 打印机和 ZPL 程序设计语言。以下是一个简单的示例程序,可以将多个二维码一次性打印到 Zebra 打印机上。 ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class BatchPrintQR { public static void main(String[] args) { try { // 读取二维码图片文件夹下的所有文件 Path dirPath = Paths.get("C:/qrcodes"); List<Path> files = Files.list(dirPath).toList(); // 打印机连接字符串 String printerConnectionString = "tcp://192.168.1.100:9100"; // 遍历所有文件生成 ZPL 命令并发送到打印机 for (int i = 0; i < files.size(); i++) { Path filePath = files.get(i); byte[] fileBytes = Files.readAllBytes(filePath); String zplCommand = "^XA^FO50,50^BQN,2,10^FDMA," + i + "^FS^XZ"; ZebraPrinter.sendZplCommand(printerConnectionString, zplCommand, fileBytes); } System.out.println("All QR Codes have been printed!"); } catch (IOException e) { e.printStackTrace(); } } } class ZebraPrinter { public static void sendZplCommand(String printerConnectionString, String zplCommand, byte[] imageData) { try { // 打印机连接 Connection connection = new TcpConnection(printerConnectionString); connection.open(); // 发送 ZPL 命令 connection.write(zplCommand.getBytes()); // 发送图片数据 if (imageData != null) { String imageStartCommand = "^GFA,"; imageStartCommand += imageData.length + ","; imageStartCommand += imageData.length + ","; imageStartCommand += "0,"; // 图片类型,0 表示黑白 imageStartCommand += " "; connection.write(imageStartCommand.getBytes()); connection.write(imageData); } // 断开连接 connection.close(); } catch (ConnectionException e) { e.printStackTrace(); } catch (ZebraPrinterLanguageUnknownException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这个程序假设所有的二维码图片都保存在 C:/qrcodes 文件夹下。程序会读取该文件夹下的所有文件,并将每个文件生成一个 ZPL 命令发送到打印机。ZPL 命令中包含了二维码图片的位置和编号,打印机会将所有的二维码一次性打印出来。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

stalin_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值