上次我們用Java生成了條形碼 地址:https://www.cnblogs.com/zhang-dongliang/p/10829763.html,這次我們來看一下二維碼
現在無處不在都是二維碼的身影,大街小巷都隨處可見,小到街道小販大到公司企業無處不在,但是二維碼是怎么生成的呢,下面我們就來看看用Java怎么生成二維碼的吧.
這次我們用到zxing首先介紹一下zxing
ZXing是一個開源的,用Java實現的多種格式的1D/2D條碼圖像處理庫,它包含了聯系到其他語言的端口。
Zxing可以實現使用手機的內置的攝像頭完成條形碼的掃描及解碼,這是一個開源的項目Git地址:https://github.com/zxing/zxing
下面進入正題首先引入pom.xml
<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.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* @author pillar
* @date 2019-05-08
*/
public class codeUtil {
/**
*二維碼實現
* @param msg
* @param path
*/
public static void getBarCode(String msg,String path){
try {
File file=new File(path);
OutputStream ous=new FileOutputStream(file);
if(StringUtils.isEmpty(msg) || ous==null)
return;
String format = "png";
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType,String> map =new HashMap<EncodeHintType, String>();
//設置編碼 EncodeHintType類中可以設置MAX_SIZE, ERROR_CORRECTION,CHARACTER_SET,DATA_MATRIX_SHAPE,AZTEC_LAYERS等參數
map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
map.put(EncodeHintType.MARGIN,"2");
//生成二維碼
BitMatrix bitMatrix = new MultiFormatWriter().encode(msg, BarcodeFormat.QR_CODE,300,300,map);
MatrixToImageWriter.writeToStream(bitMatrix,format,ous);
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String msg = "pillar666";
String path = "D:\\pillar\\pilar666.png";
codeUtil.getBarCode(msg,path);
}
}
生成圖形如下所示:

其實EncodeHintType這個類中可以設置的樣式格式還是比較多的源碼如下:
public enum EncodeHintType {
ERROR_CORRECTION,
CHARACTER_SET,
DATA_MATRIX_SHAPE,
/** @deprecated */
@Deprecated
MIN_SIZE,
/** @deprecated */
@Deprecated
MAX_SIZE,
MARGIN,
PDF417_COMPACT,
PDF417_COMPACTION,
PDF417_DIMENSIONS,
AZTEC_LAYERS,
QR_VERSION;
private EncodeHintType() {
}
}
而BarcodeFormat這個類主要是設置二維碼的類型,有好多類型可供選擇
public enum BarcodeFormat {
AZTEC,
CODABAR,
CODE_39,
CODE_93,
CODE_128,
DATA_MATRIX,
EAN_8,
EAN_13,
ITF,
MAXICODE,
PDF_417,
QR_CODE,
RSS_14,
RSS_EXPANDED,
UPC_A,
UPC_E,
UPC_EAN_EXTENSION;
private BarcodeFormat() {
}
}
現在二維碼越來越流行,有很多方法可以實現,這只是其中一種。當然如有不當之處請指出我們共同學習!
