需求:
将查询出的二维码打成压缩包批量下载
思路1:
1.查询出二维码base64值
2.转为图片
3.生成压缩包文件夹,将图片加入压缩包文件架
4.返回压缩包文件夹下载路径
出参
public class ZipVO {
private String zipFileName;
private String setHasFail;
private Integer totalSize;
}
生成压缩包
public String generateZip() {
ZipVO returnVO = new ZipVO();
File zipFile = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
try{
Long userId = 1L;
Date current = new Date();
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";
String qrCodeBase64Str = QrCodeUtil.createQrCode(code);
if (StringUtils.isNotBlank(qrCodeBase64Str)) {
qrCodeBase64Str=qrCodeBase64Str.replaceAll("data:image/png;base64,","");
byte[] buffer = new BASE64Decoder().decodeBuffer(qrCodeBase64Str);
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();
}
}
}
二维码转换工具
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;
}
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-将内容写入文件并导出到压缩包 - 沙漠中的微生物