使用Zxing二维码生成(第二种)

1、引用依赖

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.3</version>
</dependency><br>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.11</version>
</dependency>

  

2、测试生成二维码

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.client.j2se.MatrixToImageWriter;

@RestController
public class TestController {

    // 生成二维码
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response){
        // 二维码内容
        String contents = "测试二维码";
        // 表示是二维码
        BarcodeFormat qrCode = BarcodeFormat.QR_CODE;
        // 二维码宽度
        int width = 300;
        // 二维码高度
        int height = 300;
        // 返回的图片格式
        String format = "png";
        response.setContentType("image/png");
        try {
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            // 设置二维码编字符集
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 设置二维码的外间距
            hints.put(EncodeHintType.MARGIN, 10);
            // 设置二维码容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 创建二维码对象
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, qrCode, width, height, hints);
            // 输出二维码
            MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

参考:https://www.cnblogs.com/jiangyalin/p/17085249.html 

posted @ 2023-05-08 14:05  Amy清风  阅读(19)  评论(0编辑  收藏  举报