二維碼是根據必定規則生成,存儲信息的小圖片。好比能夠存儲參數存儲url等內容。掃描以後將能得到這些內容
下文爲普通二維碼的生成,可自定義二維碼的大小,定義二維碼中存儲的數據內容工具
1.下文使用的二維碼生成jar座標google
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.2</version> </dependency>
2.工具類的定義
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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;編碼
public class CodeImageUtil {url
// 默認二維碼寬度 public static final int WIDTH = 300; // 默認二維碼高度 public static final int HEIGHT = 300; // 默認二維碼文件格式 public static final String FORMAT = "png"; // 二維碼參數 public static final Map<EncodeHintType, Object> HINTS = new HashMap<EncodeHintType, Object>(); //初始化編碼格式等參數 static { // 字符編碼 HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8"); HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 二維碼與圖片邊距 HINTS.put(EncodeHintType.MARGIN, 2); } /** * * @description:功能描述 將二維碼寫出到輸出流中 * @param content 二維碼內容即要存儲在二維碼中的內容(掃描二維碼以後獲取的內容) * @param stream 輸出流 * @param width 二維碼寬 * @param height 二維碼高 * @throws WriterException * @throws IOException * @see: 須要參見的其它內容 */ public static void writeToStream(String content, OutputStream stream, Integer width, Integer height) throws WriterException, IOException { if(width==null){ width=WIDTH; } if(height==null){ height=HEIGHT; } BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, HINTS); MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, stream); }
}code
3.main中的調用
public void main(String[] arg){orm
ByteArrayOutputStream out = new ByteArrayOutputStream(); // 生成二維碼圖片 CodeImageUtil.writeToStream(url, out, 300, 300); InputStream in = new ByteArrayInputStream(out.toByteArray()); //將生成的二維碼寫入圖片,也可直接使用流 String filePath="H:\\file_station\\" + fileName; FileOutputStream fos = new FileOutputStream(filePath); int length; byte[] b = new byte[1024]; while ((length=in.read(b))>0){ fos.write(b,0,length); } fos.flush(); in.close(); fos.close();
}圖片