【java】【二维码生成】-二维码生成方式

一个简单生成二维码方式 - 速懂
这只是一个简单的生成,测试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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章