Generating 2D code in java background

Keywords: Java Google QRCode Attribute

First, define the QR code container on the front-end page to store the generated QR code in the background (the following is corresponding to the three logo icons in the above figure, which are put here to let you see more clearly!)

            <ul>
                <li><img src="/static/Images/HitArea/logo-sina.png" alt=""></li>
                <li><img src="/static/Images/HitArea/logo-friendCircle.png" alt=""></li>
                <li><img src="/static/Images/HitArea/logo-QQzone.png" alt=""></li>
            </ul>

   `<!-- Container for QR code -->
    <img  id="qrcode" style="padding-left: 20px">` 

Add onclick() event to wechat logo (my code is put in the corresponding js file, which needs to be introduced in HTML page when using, and you can also directly put it on the page

//Method in js, scan QR code with wechat
function WeiXin(){

//debugger;
//Clear QR code text box
$("#qrcode").html("");

var title = $("#commentTitle").val();
var url = window.location.href;
var url2 = url.split("localhost:8068/");
if (url2.length > 1){
    var url3 = url2[1];
    var url4 = "http://www.zhengquan51.com/" + url3;
} else{
    //If it's online or offline
    url4 = url2;
}
var icno = $("#icno").val();
if (icno == undefined || icno == null){
    icno = "";
}

//This is the main view (the function is to call the background interface and image echo)
$("#QRcode "). Attr (" src "," getcode / QRcode? Content = "+ url4); / / access the background interface according to the path, generate the QR code and display it in the container through the src attribute. Url4 is the page link content for which I need to generate the QR code.

$(".Index-Popup-Boxs").show();

}
Background code: first write the qrcode method in the controller layer. The code is as follows:
/**

 * Generate wechat picture QR code
 *
 * @param request
 * @param response
 * @param content   Is the content of the QR code transmitted from the front end, i.e. path link
 * @throws Exception
 */
@Log("Wechat picture QR code")
@GetMapping("/qrcode")
public void qrcode(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "content") String content) throws Exception {
    if (StringUtils.isBlank(content)) {
        response.sendRedirect("/404.html");
        return;
    }
    //Call tool class to generate QR code   
    RecodeUtil.creatRrCode(content, 180,180,response);   //180 is the height and width of the picture
}

Write a tool class RecodeUtil, which is stored in the utils file directory of my project. You can choose your own location and import it in the controller. The code of the tool class is as follows:

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 javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;

public class RecodeUtil {

public static void creatRrCode(String contents, int width, int height,HttpServletResponse response) {
    Hashtable hints = new Hashtable();

    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //Highest fault tolerance level
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  //Set character encoding
    hints.put(EncodeHintType.MARGIN, 1);                //Two dimensional code blank area, with a minimum of 0 and white edge, is only very small, with a minimum of about 6 pixels
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints); // 1. Read file to byte array

// ByteArrayOutputStream out = new ByteArrayOutputStream();

        BufferedImage image = toBufferedImage(bitMatrix);
        //IO stream converted to png format
        ImageIO.write(image, "png", response.getOutputStream());

// byte[] bytes = out.toByteArray();
/// / 2. Convert byte array to binary
// BASE64Encoder encoder = new BASE64Encoder();
// binary = encoder.encodeBuffer(bytes).trim();

    } catch (WriterException e) { // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
/**
 * image Stream data processing
 *
 * @author ianly
 */
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) ? 0xFF000000 : 0xFFFFFFFF);
        }
    }
    return image;
}

}
In addition, because jar uses google, it is necessary to import related dependencies in pom.xml. Here I'm ready for you! Paste the following two in the label:

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

After that, you can test it. If you have any questions, you can chat with me privately.

Original text: https://blog.csdn.net/weixin_...

Posted by EcLip$e on Mon, 28 Oct 2019 07:29:25 -0700