Maven依賴
<!-- 二維碼生成 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
壓縮工具類
package com.ruoyi.common.utils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author: 程鵬
* @date: 2021-08-31 10:53
* @Description:
*/
@Component
public class ZipUtil {
/**
* @param needZipPath 壓縮文件夾路徑
* @param out 壓縮文件輸出流
*/
public static void filetoZip(String needZipPath, OutputStream out)throws RuntimeException{
long start = System.currentTimeMillis();//計算壓縮所需要的時間
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(needZipPath);//獲取要壓縮的文件
do_file_toZip(sourceFile,zos,"barCode");//開始壓縮
long end = System.currentTimeMillis();
long useTime = end - start;//壓縮耗費的時間
System.err.println("本次壓縮,耗時" + useTime + "毫秒");
} catch (Exception e) {
throw new RuntimeException("壓縮失敗了,呵呵",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 遞歸壓縮方法
* @param sourceFile 源文件
* @param zos zip輸出流
* @param name 壓縮后的名稱
*/
private static void do_file_toZip(File sourceFile, ZipOutputStream zos, String name) throws Exception {
byte[] buf = new byte[1024 * 2];
if (sourceFile.isFile()) {
// 向zip輸出流中添加一個zip實體,構造器中name為zip實體的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip輸出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原來的文件結構時,需要對空文件夾進行處理
zos.putNextEntry(new ZipEntry(name + "/"));// 空文件夾的處理
zos.closeEntry();// 沒有文件,不需要文件的copy
} else {
for (File file : listFiles) {
// 判斷是否需要保留原來的文件結構
// 注意:file.getName()前面需要帶上父文件夾的名字加一斜杠,
// 不然最后壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了
do_file_toZip(file, zos, name + "/" + file.getName());
}
}
}
}
}
二維碼生成工具類
package com.ruoyi.common.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.CharacterSetECI;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
/**
* Author 程鵬
* Date: 2021/08/27 16:01
* Description:二維碼生成工具類
*/
@Component
public class BarcodeUtils {
private static final Color QRCOLOR = Color.black; // 二維碼顏色 默認是黑色
private static final Color BGWHITE = Color.white; // 背景顏色
public static final int WIDTH = 360;
public static final int HEIGHT = 512;
public static final int MARGIN = 2;
public static final int FONTSIZE = 20;
/**
* // 二維碼生成
*
* @param contents 說明
* @return BufferedImage
* @throws Exception
*/
public BufferedImage drawQRImage(String pressText,String contents) throws Exception {
BufferedImage qRImage = null;
if (contents == null || "".equals(contents)) {
throw new Exception("content說明不能為空");
}
// 二維碼參數設置
HashMap<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, CharacterSetECI.UTF8); // 編碼設置
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 安全等級,最高h
hints.put(EncodeHintType.MARGIN, MARGIN); // 設置margin=0-10
// 二維碼圖片的生成
BarcodeFormat format = BarcodeFormat.QR_CODE;
// 創建矩陣容器
BitMatrix matrix = null;
try {
matrix = new MultiFormatWriter().encode(contents, format, WIDTH, HEIGHT, hints);
} catch (WriterException e) {
e.printStackTrace();
}
// 設置矩陣轉為圖片的參數
MatrixToImageConfig toImageConfig = new MatrixToImageConfig(QRCOLOR.getRGB(), BGWHITE.getRGB());
// 矩陣轉換圖像
qRImage = MatrixToImageWriter.toBufferedImage(matrix, toImageConfig);
// pressText(pressText, qRImage);
return pressText(pressText, qRImage);
}
/**
* @param pressText 二維碼下方插入文字
* @param image 需要添加文字的圖片
* @為圖片添加文字
*/
public BufferedImage pressText(String pressText, BufferedImage image) throws Exception {
BufferedImage outImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
//計算文字開始的位置
//x開始的位置:(圖片寬度-字體大小*字的個數)/2
int startX = (WIDTH - (FONTSIZE * pressText.length())) / 2;
//y開始的位置:圖片高度-(圖片高度-圖片寬度)/2
int startY = HEIGHT - (HEIGHT - WIDTH) / 2 ;
int imageW = outImage.getWidth();
int imageH = outImage.getHeight();
// BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
Graphics2D g = outImage.createGraphics();
g.drawImage(image, 0, 0, imageW, imageH, null);
g.setColor(QRCOLOR);
g.setFont(new Font("微軟雅黑", Font.BOLD, FONTSIZE));
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setBackground(Color.white);
// 獲取文字數量 按照字節展示
int size = pressText.getBytes("GBK").length;
// 獲取一行最多能容納多少文字 按照文字字節展示
int maxSize = (WIDTH / FONTSIZE - 2)*2;
if (size > maxSize) {
int v = size % maxSize;
for (int a = 0; a < (size / maxSize); a++) {
// g.drawString(pressText.substring(a * maxSize, (a + 1) * maxSize), (WIDTH - (FONTSIZE * maxSize)) / 2 , startY);
String s = outStringByByte(pressText, maxSize);
g.drawString(s, (WIDTH - (FONTSIZE * (WIDTH / FONTSIZE - 2))) / 2 , startY);
pressText=pressText.substring(s.length(),pressText.length());
startY = startY + 30;
}
if (v != 0) {
g.drawString(pressText, (WIDTH - (FONTSIZE * v)) / 2 , startY);
}
} else {
g.drawString(pressText, (WIDTH-((pressText.getBytes("GBK").length)/2)*FONTSIZE)/2 , startY);
}
g.dispose();
return outImage;
}
/**
* 保存二維碼圖片到本地
* @param contents
* @throws Exception
*/
public void createImg(String pressText,String contents,String filename,String filePath) throws Exception {
BufferedImage qRImageWithLogo = drawQRImage(pressText,contents);
// 寫入返回
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(qRImageWithLogo, "jpg", baos);
//圖片類型
String imageType = "jpg";
//生成二維碼存放文件
File file = new File(filePath+filename+".jpg");
if(!file.exists()){
file.mkdirs();
}
ImageIO.write(qRImageWithLogo, imageType, file);
baos.close();
}
/**
* @param fileName 文件名字
* @param path 路徑 具體到要下載的文件名字
* @param delete 下載完成是否刪除
* @param response
* @return
*/
public String downLoadFile(String fileName, String path,boolean delete, HttpServletResponse response) {
try {
File file = new File(path);
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
response.setContentLength((int) file.length());
//定義輸出類型
response.setContentType("application/zip");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream buff = new BufferedInputStream(fis);
//相當於我們的緩存
byte[] b = new byte[1024];
//該值用於計算當前實際下載了多少字節
long k = 0;
//從response對象中得到輸出流,准備下載
OutputStream myout = response.getOutputStream();
//開始循環下載
while (k < file.length()) {
int j = buff.read(b, 0, 1024);
k += j;
myout.write(b, 0, j);
}
myout.flush();
fis.close();
buff.close();
if (delete) {
file.delete();
}
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public void deleteDir(String path){
File file = new File(path);
if(!file.exists()){//判斷是否待刪除目錄是否存在
System.err.println("The dir are not exists!");
}
String[] content = file.list();//取得當前目錄下所有文件和文件夾
for(String name : content){
File temp = new File(path, name);
if(temp.isDirectory()){//判斷是否是目錄
deleteDir(temp.getAbsolutePath());//遞歸調用,刪除目錄里的內容
temp.delete();//刪除空目錄
}else{
if(!temp.delete()){//直接刪除文件
System.err.println("Failed to delete " + name);
}
}
}
file.delete();
}
private static String outStringByByte(String str, int len) throws IOException {
byte[] btf = str.getBytes("gbk");
int count = 0;
for (int j = len - 1; j >= 0; j--) {
if (btf[j] < 0)
count++;
else
break;
}
if (count % 2 == 0)
return new String(btf, 0, len, "gbk");
else
return new String(btf, 0, len - 1, "gbk");
}
}