首先引入依赖
<!-- 谷歌生成二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;
public class QrCodeUtils {
/**
* 返回二维码字节数组 , 转为base加密,返回String
*
* @param text
* @param width
* @param height
* @return
* @throws WriterException
* @throws IOException
*/
public static String getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 0);//去除多余白边, 数字越小,白边越小.为0时 没有白边
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
//base64编码
BASE64Encoder encoder = new BASE64Encoder();
String png_base64 = encoder.encodeBuffer(pngData).trim();//转换成base64串
png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
return png_base64;
}
public static void main(String[] args) {
try {
String qrCodeImage = getQRCodeImage("http://www.baidu.com", 350, 350);
System.out.println("值为:" + "data:image/jpg;base64," + qrCodeImage);
} catch (WriterException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}