通過JAVA生成二維碼的方式主要有兩種(ZXing和QRCode),此次實現的代碼採用的是google公司提供的ZXing二維碼生成器。
第一步:導包
第二步:代碼實現
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
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.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
/**
* 二維碼生成測試
* @author Administrator
*
*/
public class QRCodeTest {
//生成二維碼
public void QRcode() throws WriterException, IOException{
String FileName = "ZXing.jpg"; //文件名稱
String FilePath = "d:/"; //文件保存地址
/**
* 可以通過json格式來進行數據跳轉,同樣也可以通過String來進行寫相關的代碼或信息
*/
//創建JSON解析器(阿里巴巴)
//JSONObject json = new JSONObject();
//json.put("baidu", "https://www.baidu.com/");
//將JSON數據轉換成字符類型
//String content = json.toJSONString();
//設置跳轉地址(如果需要直接跳轉應直接採用String 數據類型進行跳轉)
String content = "https://www.baidu.com/";
int width = 200; //設置二維碼圖片寬度
int height = 200; //設置二維碼圖片高度
String format = "jpg"; //設置二維碼圖像類型
Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
//設置輸出格式
hint.put(EncodeHintType.CHARACTER_SET, "UTF8");
//生成矩形(MultiFormatWriter是一個工廠類,根據傳入的參數生相應的條碼)
BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hint);
//指定圖像生成後保存路徑並指定名字
Path path = FileSystems.getDefault().getPath(FilePath, FileName);
//寫出編碼到指定路徑(傳入參數代碼的格式、圖像的類型、圖像生成後的路徑),該方法在javase-3.0.jar版本後已封裝到JAR包中
MatrixToImageWriter.writeToPath(bm, format, path);
System.out.println("輸出成功!");
}
}