最近接到一个生成二维码的任务,根据某个网址生成批量二维码,然后扫描跳转网页
删除源文件我用的commonsIO包,下面是maven
<dependency> <groupId>org.apache.commons.io</groupId> <artifactId>commonsIO</artifactId> <version>2.5.0</version> <type>pom</type> </dependency>
serviceimpl逻辑代码
package com.thundersdata.backend.basic.service.impl;
import com.google.zxing.WriterException;
import com.thundersdata.backend.basic.dao.UniqueCodeMapper;
import com.thundersdata.backend.basic.dto.GenerateUniqueCodeDTO;
import com.thundersdata.backend.basic.model.UniqueCode;
import com.thundersdata.backend.basic.service.UniqueCodeService;
import com.thundersdata.backend.basic.utils.GenerateNum;
import com.thundersdata.backend.basic.vo.UniqueCodeVO;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static com.thundersdata.backend.common.utils.QrCodeCreateUtil.createQrCode;
/**
* @Author: wrc
* @Classname UniqueCodeServiceImpl
* @Description TODO
* @Date 2020/4/20 11:36
* @Created wrc
*/
@Service
public class UniqueCodeServiceImpl implements UniqueCodeService {
@Autowired
private UniqueCodeMapper uniqueCodeMapper;
//二维码地址
@Value("${upload.UniqueCode}")
private String UQPATH ;
//访问网页地址
private static String WEBSITE = "https://www.cnblogs.com/zuidongfeng/p/9853335.html";
/**
* 生成唯一码 返回压缩包路径
* @param generateUniqueCodeDTO
* @return
*/
@Override
public String generateUcode(GenerateUniqueCodeDTO generateUniqueCodeDTO) throws Exception {
//获取随机生成的唯一码,这些都是我的业务代码,大家可以直接略过
List<UniqueCode> codes = GenerateNum.getNewEquipmentNo(generateUniqueCodeDTO);
File file = new File(UQPATH+"\\"+String.valueOf(System.currentTimeMillis()));
if(!file.isDirectory()){
file.mkdirs();
}
for(int i=0;i<codes.size();i++){
//这个方法是生成二维码
createQrCode(new FileOutputStream(new File(file+"\\"+codes.get(i).getCode()+".jpg")),
WEBSITE,900, "JPEG");
}
FileOutputStream fos1 = new FileOutputStream(file+".zip");
//压缩文件夹
GenerateNum.toZip(file, fos1,true);
uniqueCodeMapper.generatorUniqueCode(codes);
fos1.close();
//压缩完以后一定要释放资源,不然源文件夹删不掉的
System.gc();
//删除源文件夹
FileUtils.deleteDirectory(file);
return file+".zip";
}
}
生成二维码的方法,可以直接扫码
/**
* 生成包含字符串信息的二维码图片
*
* @param outputStream 文件输出流路径
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
* @param imageFormat 二维码的格式
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
//设置二维码纠错级别MAP
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 200, matrixWidth - 200, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i - 100, j - 100, 1, 1);
}
}
}
return ImageIO.write(image, imageFormat, outputStream);
}
这是读取二维码的方法,测试用
/**
* 读二维码并输出携带的信息
*/
public static void readQrCode(InputStream inputStream) throws IOException {
//从输入流中获取字符串信息
BufferedImage image = ImageIO.read(inputStream);
//将图像转换为二进制位图源
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
e.printStackTrace();
}
System.out.println(result.getText());
}
压缩文件夹方法
/**
*
* @param sourceFile 源文件路径
* @param out 输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* @throws RuntimeException
*/
public static void toZip(File sourceFile, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static final int BUFFER_SIZE = 2 * 1024;
/**
80 * 递归压缩方法
81 * @param sourceFile 源文件
82 * @param zos zip输出流
83 * @param name 压缩后的名称
84 * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
85 * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
86 * @throws Exception
87 */
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);
}
}
}
}
}