java生成二維碼圖片

基於zxing的二維碼實現 java

pom引入依賴

<!-- 二維碼生成依賴 -->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>${core.version}</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>${javase.version}</version>
		</dependency>

具體方法如下

如下兩種方式 第一種是直接生成二維碼圖片
第二種是生成二維碼字節數組

package com.wzx.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

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;

public class QRCodeGeneratorUtils {

	// 生成二維碼圖片
	/**
	 * @param text 輸入二維碼的內容
	 * @param width  二維碼的寬度
	 * @param height  二維碼的高度
	 * @param filePath  存放二維碼的路徑
	 * @throws WriterException  異常類型
	 * @throws IOException  異常類型
	 */
	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);

	}

	// 生成二維碼字節數組
	public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
		ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
		MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
		byte[] pngData = pngOutputStream.toByteArray();
		return pngData;
	}
}

方法調用

byte[] b = QRCodeGeneratorUtils.getQRCodeImage(text, 200, 200);
String base64Str = Base64Helper.encode(b);
return base64Str;
// 返回的是 Base64 前段接受需要轉一下 加上: data:image/png;base64,
//if(res.data.status){
//	 this.imgSrc = 'data:image/png;base64,' + res.data.result; 
//}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章