一個簡單生成二維碼方式 - 速懂
這只是一個簡單的生成,測試jar工具是否有用,簡潔易懂點
<!-- 生成二維碼 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
/**
* @ClassName: QRCodeGenerator
* @Author mingjia.xu
* @Date 2020-04-14 & 17:36
* @Describes
*/
@Slf4j
public class QRCodeGenerator {
private static final String QR_CODE_IMAGE_PATH = "/Volumes/Data/er_wei_ma/aaa/MyQRCode.png";
private static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException,IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
log.info("生成成功");
}
public static void main(String[] args) {
try {
generateQRCodeImage("This is my first QR Code11", 350, 350, QR_CODE_IMAGE_PATH);
} catch (WriterException e) {
log.info("Could not generate QR Code, WriterException :: " + e.getMessage());
} catch (IOException e) {
log.info("Could not generate QR Code, IOException :: " + e.getMessage());
}
}
}
– 友情提醒下:上面的已經是簡單二維碼生成代碼了,下面的是我運用在項目上的代碼,需要要參考就可以往下看,不需要就不必要看的了。
接下來是我用在項目上的代碼
需求:批量生成二維碼打包成壓縮包返回前端提供下載(*.zip)
實現步驟:文件夾存在 - 生成二維碼 - 放入文件夾 - 打包成zip - 返回response - 刪除zip與文件夾
實現原理解釋:先要確定生成文件夾位置是否存在,不存在就生成,然後將生成的二維碼全部放入文 件夾中,將文件夾打包成zip,返回流給前端,同時刪除包
- 代碼塊:(總共分割成4塊代碼,全放一個方法裏不易讀)
- batchProduceQRCode() - 在ServiceImpl層寫個接口方法
- QRCodeUtil.generateQRCode() - 調用二維碼生成工具類其一方法
- ZipUtils.toZip() - 需要調用壓縮工具類其一方法
- FileUtils.deleteDirectory() - file工具類其一方法,刪除文件夾
batchProduceQRCode() -1
/**
* 批量生成二維碼
* @param store 店鋪對象(個人業務需求,用在二維碼生成內容上)
* @return 返回打包的zip地址
* @throws WriterException
* @throws IOException
*/
@Override
public void batchProduceQRCode(Store store, HttpServletResponse response, HttpServletRequest request) throws WriterException, IOException {
List<Table> tables = this.findAllByStoreId(store.getId());
//圖片生成地址路徑,在當前項目的絕對路徑去做起始加入qrcode文件夾 --- 1
String pathUrl = String.format("%s/%s/",System.getProperty("user.dir"),"qrcode");
File file = new File(pathUrl);
if (!file.exists()) {
file.mkdir();
}
//循環生成二維碼 --- 2
for (Table table : tables) {
String c = table.getQrcode().toString();
String w = store.getSetting().getTableQRCodePassword();
//二維碼內容
String text = String.format("%s?c=%s&w=%s",appProperties.getQrCodeUrl(),c,w);
String fileName = String.format("%s.png",table.getName());
QRCodeUtil.generateQRCode(text,350,350,pathUrl+"/"+fileName);
log.info("生成二維碼圖片完成");
}
//流 --- 3
response.setContentType("application/json");
String agent = request.getHeader("user-agent");
String filename = FileUtils.encodeDownloadFilename("qrcode.zip", agent);
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
ServletOutputStream outputStream = response.getOutputStream();
//壓縮 --- 4
ZipUtils.toZip(pathUrl, outputStream,true);
outputStream.flush();
outputStream.close();
//刪除生成的文件夾 --- 5
FileUtils.deleteDirectory(pathUrl);
}
QRCodeUtil 二維碼生成類 -2
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
/**
* @ClassName: QRCodeUtil
* @Author mingjia.xu
* @Date 2020-04-08 & 14:14
* @Describes 二維碼生成工具類(當前只有簡單的png生成,
* jar還可以插入圖片logo進二維碼,我就簡單的放一個方法吧)
*/
public class QRCodeUtil {
/**
* 生成二維碼
*
* @param text 內容
* @param width 圖片寬度
* @param height 圖片長度
* @param filePath 生成圖片地址
* @throws IOException
*/
public static void generateQRCode(String text, int width, int height, String filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
bitMatrix.clear();
}
}
ZipUtils.toZip() -3 壓縮文件夾工具類
/**
* @ClassName: ZipUtils
* @Author mingjia.xu
* @Date 2020-04-08 & 14:14
* @Describes zip壓縮工具
*/
@Slf4j
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 壓縮成ZIP 方法1
*
* @param srcDir 壓縮文件夾路徑
* @param out 壓縮文件輸出流
* @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構;
* false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
* @throws RuntimeException 壓縮失敗會拋出運行時異常
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
log.info("壓縮完成,耗時:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 壓縮成ZIP 方法2
*
* @param srcFiles 需要壓縮的文件列表
* @param out 壓縮文件輸出流
* @throws RuntimeException 壓縮失敗會拋出運行時異常
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
log.info("壓縮完成,耗時:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 遞歸壓縮方法
*
* @param sourceFile 源文件
* @param zos zip輸出流
* @param name 壓縮後的名稱
* @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構;
* false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
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);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原來的文件結構時,需要對空文件夾進行處理
if (KeepDirStructure) {
// 空文件夾的處理
zos.putNextEntry(new ZipEntry(name + "/"));
// 沒有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判斷是否需要保留原來的文件結構
if (KeepDirStructure) {
// 注意:file.getName()前面需要帶上父文件夾的名字加一斜槓,
// 不然最後壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
public static void main(String[] args) throws Exception {
/** 測試壓縮方法1 */
// FileOutputStream fos1 = new FileOutputStream(new File("/Volumes/Data/er_wei_ma/MyQRCode.zip"));
// ZipUtils.toZip("/Volumes/Data/er_wei_ma/qwe", fos1, true);
/** 測試壓縮方法2 */
// List<File> fileList = new ArrayList<>();
// fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
// fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
// FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));
// ZipUtils.toZip(fileList, fos2);
}
}
FileUtils.deleteDirectory() -4 刪除工具類,這個你可要可不要
public class FileUtils {
/**
* 刪除文件目錄
* @param path
* @throws IOException
*/
public static void deleteDirectory(String path) throws IOException {
File folder = new File(path);
org.apache.commons.io.FileUtils.deleteDirectory(folder);
}
}