图片打包Zip压缩包文件流给前端
前言:
本文实现将图片打包成zip流返回给前端,图片来源可以是OSS存储中获取的url下载,也可以是字节生成的图片字节流,直接打包成zip文件给前端
需要代码源码可以私信我获取
1.导入包
<!-- 二维码需要 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 图片转换需要 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.24</version>
</dependency>
2.工具类
package com.qrcode.until;
/**
* @ClassName QRCodeUtils
* @Date 2023/3/29 9:53
* @Author legend
*/
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 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.Base64;
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 二维码内容
* @throws Exception
*/
public static BufferedImage generateQrCodeBack( String qrCodeContent) throws Exception {
BufferedImage image = generateQrCode(qrCodeContent, "jpg");
Graphics g = image.getGraphics();
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
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 = Base64.getEncoder().encodeToString(b);
// Base64编码
return base64String;
}
}
3.生成二维码(代码片段)
for (String uuid : uuidArray) {
//使用zxing 生成二维码
bufferedImage = QRCodeUtils.generateQrCodeBack(uuid);
log.info("二维码生成成功");
byte[] bytes = imageToBytes(bufferedImage);
//MockMultipartFile 需要导入spring-test的依赖包
/*这里自定义流程 可以将图片上传到OSS 也可以直接获取生成的图片输出
* 本段代码实现的是直接将图片输出
* */
hashMap.put(uuid, bytes);
log.info("完成");
}
4.将图片打包成zip(代码片段)
for (Map.Entry<String, byte[]> entry : hashMap.entrySet()) {
// 获取到oss的图片路径,使用上传到Oss放开这两行代码
// URL url = new URL(entry.getValue());
// imageInputStream = url.openStream();
imageInputStream= new ByteArrayInputStream(entry.getValue());
//二维码图片名称
ZipEntry zipEntry = new ZipEntry(entry.getKey() + ".jpg");
zipOutputStream.putNextEntry(zipEntry);
int len;
// 定义每次读取的字节数组
byte[] buffer = new byte[1024];
log.info("开始写入zip");
while ((len = imageInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
5.将图片转换成字节数组
private byte[] imageToBytes(BufferedImage bImg) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(bImg, "jpg", out);
} catch (IOException e) {
log.error("转成字节数组异常",e);
}
return out.toByteArray();
}