1. 程式人生 > 實用技巧 >使用java生成二維碼

使用java生成二維碼

程式碼如下:

package com.ckf.code.code;

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;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/** * @author 安詳的苦丁茶 * @date 2020/7/30 22:32 */ public class Qrcode { @Test public void generateQrcode() throws WriterException, IOException { //生成二維碼 JSONObject jsonObject = new JSONObject(); //給jsonObject物件中存資料 jsonObject.put("company", "https://www.cnblogs.com/ckfeng
"); jsonObject.put("Name", "ccc"); jsonObject.put("author", "ckf"); jsonObject.put("address", "GuangDongZhanJiang"); String content = jsonObject.toString(); //定義圖片的大小 int width = 300; int height = 300; //建立一個map集合 Map<EncodeHintType, Object> hint = new
HashMap<EncodeHintType, Object>(); //定義二維碼儲存路徑以及命名 String filePath="F://"; String fileName="QRCode.jpg"; //建立一個矩陣物件 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hint); //建立一個路徑物件 Path path= FileSystems.getDefault().getPath(filePath,fileName); //將矩陣物件生成一個圖片(二維碼) MatrixToImageWriter.writeToPath(bitMatrix,"jpg",path); System.out.println("生成二維碼"); } }