java生成二维码打印到浏览器

时间:2021-02-14 19:54:03

java生成二维码打印到浏览器

 

解决方法:

pom.xml的依赖两个jar包:

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->

<dependency>

<groupId>com.google.zxing</groupId>

<artifactId>core</artifactId>

<version>3.2.1</version>

</dependency>

<dependency>

<groupId>com.google.zxing</groupId>

<artifactId>javase</artifactId>

<version>3.2.1</version>

</dependency>

源码:

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;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

try {

String payurl = "weixin://wxpay/bizpayur?";

//生成二维码

Map<EncodeHintType, Object>  hints=new HashMap<EncodeHintType, Object>();

// 指定纠错等级

hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

// 指定编码格式

hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

hints.put(EncodeHintType.MARGIN, 1);

BitMatrix bitMatrix = new MultiFormatWriter().encode(payurl,BarcodeFormat.QR_CODE, defaultWidthAndHeight, defaultWidthAndHeight, hints);

OutputStream out = response.getOutputStream();

MatrixToImageWriter.writeToStream(bitMatrix, "png", out);//输出二维码

out.flush();

out.close();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}