Java generates QR code for WeChat, Alipay, DingTalk, etc.

Two jar packages are required: core.jar and javase.jar under com.google.zxing

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.1</version>
</dependency>

<dependency>

<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.1</version>

</dependency>


java code

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;


import com.google.common.collect.Maps;
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;


public class QRCodeUtil {


private static final int width = 300;// 默认二维码宽度
private static final int height = 300;// 默认二维码高度
private static final String format = "png";// Default QR code file format
private static final Map<EncodeHintType, Object> hints = Maps.newHashMap();// QR code parameters


static {
hints.put(EncodeHintType.CHARACTER_SET , "utf-8");// Character encoding
// Error tolerance level L, M, Q, H where L is the lowest, H is the highest
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType. MARGIN, 2);// QR code and image margins
}


/**
* Returns a BufferedImage object

* @param content
* QR code content
*/
public static BufferedImage toBufferedImage(String content)
throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}


/**
* Output the QR code image to a stream

* @param content
* QR code content
* @param stream
* Output stream
*/
public static void writeToStream(String content, OutputStream stream)
throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
}


/**
* Generate 2D Code image file

* @param content
* QR code content
* @param path
* file save path
*/
public static void createQRCode(String content, String path)
throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// toPath() 方法由 jdk1.7 及以上提供
MatrixToImageWriter.writeToPath(bitMatrix, format, new File(path).toPath());
}public static void main(String[] args) {try {createQRCode("https://www.baidu.com", "D://1111.png");} catch (Exception e) {e.printStackTrace();}}










}


@RequestMapping("getQRCode.do")
public void getQRCodeImg(HttpServletRequest request, HttpServletResponse response) {
// 响应头
response.setDateHeader("expires", 0);
response.setHeader("Cache-control", "no-store,no-cache,must-revalidate");
response.addHeader("Cache-Control", "post-check=0,pre-check=0");
response.setHeader("pragma", "no-cache");
response.setContentType("image/jpeg");String content= "www.baidu.com";try {// 响应流中绘制二维码QRCodeUtil.writeToStream(content, response.getOutputStream());} catch (Exception e) {e.printStackTrace();}










jsp

<body>

            <img class="mt20 mb30" alt="二维码" src="/getQRCode.do"/>

</body>


-------------------------------------------------- -----This is the dividing line----------------------------------------- -----------------------

Insert a logo image into the QR code

/**

* Generate QR code

* @param content The content to be written in the
QR code* @param imgPath The address of the logo image in the middle of the QR code
* @param output Output stream
* @param needCompress Whether the logo image needs to be compressed
* @throws Exception
*/
public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
throws Exception {
BufferedImage image = createImage(content, imgPath, needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}

/**
* Create QR code
*/

private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {

Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 设置字符集
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
// 设置边框
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH,
QRCODE_HEIGHT, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
                //If the logo image path is empty, the generated QR code has no logo
if (imgPath == null || "".equals(imgPath)) {
return image;
}


QRCodeCreator.insertImage(image, imgPath, needCompress);
return image;

}


/**
* 二维码中插入LOGO图片
*/
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println("" + imgPath + " 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) {
// 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_WIDTH - width) / 2;
int y = (QRCODE_HEIGHT - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();

}


-------------------------------------------------- ----- is the dividing line again ^_^-------------------------------------- ----

public void createWxQRCode() {

                int width = 280;
int height = 280;
// QR code image format
Hashtable hints = new Hashtable();
// Content encoding
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BufferedImage image = null;
ServletOutputStream out = null;
try {
// QR code information
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
bitMatrix = deleteWhite(bitMatrix);
// Create 2D code
image = toBufferedImage(matrix);
try {
out = response.getOutputStream();
ImageIO.write(image, "gif", out);
image.flush();
out.flush();
} finally {
if (out ! = null) {
try {
out.close();
} catch (Exception e) {}}}} catch (Exception e) {}







}

         /**
 *   去掉白边
 */
public static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}

public static BufferedImage toBufferedImage(BitMatrix matrix) {

int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;

}




The above are the ones that I personally tested successfully. If you have any questions, please ask them to make progress together, thank you, and gradually improve. . .


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324602192&siteId=291194637