java生成二维码图片

这次我们用到zxing首先介绍一下zxing,ZXing(“斑马线”)是一种开放源代码,多格式的1D / 2D条码图像处理库,以Java实现,并带有其他语言的端口。

Zxing可以实现使用手机的内置的摄像头完成条形码的扫描及解码,这是一个开源的项目  Git地址:https://github.com/zxing/zxing

1.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>
2.test 代码
  
/**
*二维码实现
* @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";
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 ="maodoudou";
String path = "/Users/ww/Desktop/gitwork/whl.png";
getBarCode(msg,path);

}
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() {
    }
 }
posted @ 2019-11-27 16:07  wyuioahxvm  阅读(207)  评论(0编辑  收藏  举报