java——使用zxing生成二维码

  1. 新建一个类,在main方法中运行或测试方法即可。
  2. 引入关于zxing的maven依赖,如果不是maven项目也可以直接下载jar包引入。

    com.google.zxing
    core
    3.3.3


    com.google.zxing
    javase
    3.3.3


3.直接粘代码

package com.zxing;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.security.spec.EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Client02ApplicationTests {

   //生成二维码
   @Test
   public void contextLoads() throws WriterException, IOException {
      String filePath = "d://";//路径
      String fileName = "test.jpg";//图片名称
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("userId","123456");
      jsonObject.put("username","张三");
      jsonObject.put("age","20");
      String content = jsonObject.toJSONString();//内容
      int height = 200;
      int width = 200;
      String format = "jpg";//格式
      Map hints = new HashMap<>();
      hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");//设置编码格式
      BitMatrix bitMatrix = new MultiFormatWriter()
            .encode(content, BarcodeFormat.QR_CODE,width,height,hints);
      Path path = FileSystems.getDefault().getPath(filePath, fileName);
      MatrixToImageWriter.writeToPath(bitMatrix,format,path);//输出图片
      System.out.println("输出成功");

   }

4.看结果图

java——使用zxing生成二维码_第1张图片

你可能感兴趣的:(开发)