Java - 批量生成二维码压缩包

需求:
将查询出的二维码打成压缩包批量下载
思路1:
1.查询出二维码base64值
2.转为图片
3.生成压缩包文件夹,将图片加入压缩包文件架
4.返回压缩包文件夹下载路径
出参
public class ZipVO {
    private String zipFileName;
    private String setHasFail; //是否有可下载文件
    private Integer totalSize;
}
生成压缩包
/**
 * 根据条件查询码值,并转换为二维码生成压缩包
 * return 压缩包下载地址
 */
public String generateZip() {

        // 返回结果
        ZipVO returnVO = new ZipVO();
        // 声明文件格式
        File zipFile = null;
        // 文件 输出流
        FileOutputStream fos = null;
        // zip 输出流
        ZipOutputStream zos = null;

        try{
			// 根据用户id生成文件夹
            Long userId = 1L;
            Date current = new Date();
            // 上传文件路径:唯一指定文件夹 userId_用户id
            String zipFilePath = " C:/Users/excl/" + "userId_" + userId  + "/";

            // 根据条件获得学生列表
            List<String> codeList = {查询sql...};
            if (CollectionUtils.isNotEmpty(codeList)) {
            
                // 创建上传文件夹
                File file = new File(zipFilePath);
                // 如果不存在就创建
                if (!file.exists()) {
                    file.mkdirs();
                }

                // 在此路径下创建压缩包
                String zipFileName = "qrcode_" + current.getTime() + ".zip";
                String zipFileNamePath = zipFilePath + zipFileName;
                zipFile = new File(zipFileNamePath);
                zipFile.createNewFile();
                fos = new FileOutputStream(zipFile);
                zos = new ZipOutputStream(fos);

                for (String code : codeList) {
                    String imgFileName = code + ".png";
                 
                    // 转为base64码值
                    String qrCodeBase64Str = QrCodeUtil.createQrCode(code);
                    if (StringUtils.isNotBlank(qrCodeBase64Str)) {
                        qrCodeBase64Str=qrCodeBase64Str.replaceAll("data:image/png;base64,","");
                        byte[] buffer = new BASE64Decoder().decodeBuffer(qrCodeBase64Str);
                        // 创建zip实体,添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(imgFileName);
                        zos.putNextEntry(zipEntry);

                        // 读取待压缩的文件并写入压缩包
                        zos.write(buffer);
                        zos.flush();
                    }
                }

                //最终记得要关闭流
                zos.close();

                // 返回压缩包名
                returnVO.setZipFileName(zipFileName);
                returnVO.setTotalSize(codeList.size());
                returnVO.setHasFail(false);

            } else {
                // 无可下载压缩包
                returnVO.setTotalSize(codeList.size());
                returnVO.setHasFail(true);
            }

            return returnVO.getZipFileName();

        } catch (Exception e){
            log.error("方法异常 >>>>>>>>>>> :", e);
        } finally {
            try {

                if(fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
二维码转换工具
/**
 * 生成二维码
 * @author GaoToString
 * @create 2022-08-20 19:12
 **/
public class QrCodeUtil {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    static String writeToFile(BitMatrix matrix) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        String images = Base64.encode(stream.toByteArray());
        return "data:image/png;base64,"+images;
    }

    /**
     * @note  链接生成base64图片流
    */
    public static String createQrCode(String url) {
        try {
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
           return writeToFile(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

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

    public static void main(String[] args) {
        System.out.println(createQrCode("123"));
    }
}

参考文章:
JAVA-将内容写入文件并导出到压缩包 - 沙漠中的微生物

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值