The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
java 快速开发二维码生成服务

1. preface

I don't know when it started, but our lives were suddenly filled with QR codes. Even the auntie's egg cake breakfast stand on the street was posted with QR codes. Moreover, QR codes were also used for the control of this epidemic to avoid cross-infection caused by manual filling. so Java How to develop QR code functions? Let's have a brief discussion today.

2. About QR code

As developers, we will definitely think that QR codes are patterns that encode content into QR codes. We don't need to know how it works, it's just a process of encoding and decoding. But we still need to know something about QR codes during development:

  • Exactly the same QR code has exactly the same content as long as the algorithm is consistent, and the contrary does not hold true.
  • The more content the QR code, the more complex it is, which can be seen with the naked eye from the image of the QR code. Which means the more time it takes to decode.
  • QR codes have a fault tolerance rate. The higher the fault tolerance rate, the greater the amount of information the QR codes contain.

Based on the above points, we will make some adjustments based on actual conditions during development, and I will talk about my own experience later.

3. Java implements the generation of QR codes

usually we use Google open source 1D/2D Bar code image processing library ZXing to achieve it. We can integrate QR code generation functionality by introducing its dependencies:

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

Then we can generate a QR code using the following few lines of code and save it locally:

QRCodeWriter qrCodeWriter = new QRCodeWriter();
#The first parameter is the content of the QR code, the second parameter remains unchanged, the third and fourth parameters are width and height in turn
BitMatrix bitMatrix = qrCodeWriter.encode("https://www.felord.cn", BarcodeFormat.QR_CODE, 30, 30);
#Save the QR code as a png local image.
MatrixToImageWriter.writeToPath(encode, "png", Paths.get("E:\\workbase\\qr.png"));

If you want to control the encoded character set and error correction rate, the above code can be changed to:

QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, Object> hints = new HashMap<>();
   hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
   hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
BitMatrix bitMatrix = qrCodeWriter.encode("https://www.felord.cn", BarcodeFormat.QR_CODE, 80, 80,hints);
#Save the QR code as a png local image.
MatrixToImageWriter.writeToPath(encode, "png", Paths.get("E:\\workbase\\qr.png")); 

in fact MatrixToImageWriter Not only does it provide saving QR codes as files, but it can also be converted into streams:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix,"png",byteArrayOutputStream);

byte[] bytes = byteArrayOutputStream.toByteArray();
String base64Image = new BASE64Encoder().encode(bytes);

generated base64Image We can display it on the front end in the following ways:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQAQAAAACmas8AAAAAvklEQVR42tXSsRGDMAwFUKWxV0jl
rGY39gpOg6BxVoDGWQ0aewVorOQOzgeCARJVr9G/rzsB1YEfZgHh5QjIiPn1zoVTu6SsOLPIdMEh
2BMxJ1lzK0FYq4GRqJgWt76V5e665Na1HQ1F09/oSIpu6qaIRxaztG5pOZXrmy1sRzPjqJ7EKIQ2
Ye27o8clD4ETJxrB0JHfg7xqOAvIrtgGGTFH3XhObS3ABTHn+UQXXAROTI88a04QGB6R8Q9e+QOH
lnNzjaH0oAAAAABJRU5ErkJggg=="  alt="">

Base64 There is no problem displaying a small QR code, if generated Base64 A longer string will cause greater rendering consumption. The pros and cons must be weighed in actual production.

4. dynamic QR code

If we need to generate QR codes dynamically, or in other words, use QR codes as a service. We can use Servlet To implement a dynamic QR code service. we use Spring MVC to achieve:

package cn.felord.qr.format;

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 org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dax
 * @since 2020/2/29 21:09
 */
@Controller
@RequestMapping("/qr")
public class QRController {

    @GetMapping("/felord")
   public void gen(HttpServletResponse response) throws IOException, WriterException {

       response.setContentType("image/png");
       ServletOutputStream outputStream = response.getOutputStream();
       outputStream.write(imageBytes());
       outputStream.flush();
       outputStream.close();
   }


   private byte [] imageBytes() throws IOException, WriterException {
       QRCodeWriter qrCodeWriter = new QRCodeWriter();

       Map<EncodeHintType, Object> hints = new HashMap<>();
       hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
       hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");

       BitMatrix bitMatrix = qrCodeWriter.encode("https://www.felord.cn", BarcodeFormat.QR_CODE, 80, 80,hints);

       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
       MatrixToImageWriter.writeToStream(bitMatrix,"png",byteArrayOutputStream);
      return byteArrayOutputStream.toByteArray();
   }

}

5. Some practical experiences

In actual production, we should pay attention to the following points:

  • Try to avoid transmitting sensitive plaintext information in QR codes, and should be summarized or desensitized.
  • For relatively long URLs, short URL services should be used to reduce the information load of QR codes.
  • Try to ensure the uniqueness of the QR code within a certain period of time, such as adding some meaningless random values.
  • In fact, there are other powerful out-of-the-box zxing secondary encapsulation libraries available, such as qrext4j

6. summary

today Java This paper discusses the development of QR codes, from some characteristics of QR codes to ZXing's generation of QR codes and development of them as services. Finally, it lists some key points in actual use, hoping it will be useful to you. Welcome to express your opinions and questions through leave a message.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/4462.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

量推奥玩娱乐电光流光版+大联盟
Volume promotion of Olympic Games Entertainment Lightning Flash Edition + Major League
Someone bought it 6 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish