web123456

Java - Generate QR codes - Two ways: ordinary QR codes and intermediate logs (simple, efficient, popular, easy to understand)

Recently, the company's project requires the generation of QR codes to provide users with scan codes to jump to the page. The requirement is very simple. It happened that this is the first time I made QR codes, so I wrote this article for reference by latecomers!

I will say a few more words here. In fact, QR code is another form of presentation of a certain URL. Thinking according to logic, first, how to generate a QR code? Second, how to maintain the timeliness or effectiveness of QR codes? Let's look at the following questions:

In fact, there are many examples or tool classes for QR code generation on the Internet, but when I use it, I always feel that it is not very good. Some of the generated QR codes with intermediate LOGs are not black and white (our product manager said that black and white QR codes look formal!), and some of the generated QR codes will leave temporary files on the local server. This kind of file is a junk resource for us developers. We also have to write code to process these resources, and the amount of code becomes larger, which is not cost-effective. So I borrowed from various source codes on the Internet and wrote a tool class for your reference:

1. Because mine ismavenProject, so first introduce related jar packages

<dependency>
   <groupId></groupId>
   <artifactId>javase</artifactId>
   <version>3.1.0</version>
</dependency>

2. Directly upload the code

The code is full of comments, pay attention to the red comments I marked

-----------------------------------------------------------------------------------------------------------------------------

package ;
import ;
import ;
import .Graphics2D;
import ;
import ;
import ;
import ;
import ;
import ;

import .Base64;
import .;
import ;
import ;
import ;

import ;
import ;
/**
 * Created by healer on 2019/7/29.
 */
public class QrCodeUtil {

    private static final int QRCOLOR = 0xFF000000; // Default is black    private static final int BGWHITE = 0xFFFFFFFF; // Background color
    private static final int WIDTH = 400; // QR code width    private static final int HEIGHT = 400; // The QR code is high
    // Used to set QR QR code parameters    private static Map&lt;EncodeHintType, Object&gt; hints = new HashMap&lt;EncodeHintType, Object&gt;() {
        private static final long serialVersionUID = 1L;
        {
            put(EncodeHintType.ERROR_CORRECTION, );// Set the error correction level of QR code (H is the highest level) specific level information            put(EncodeHintType.CHARACTER_SET, "utf-8");// Set the encoding method            put(, 0);
        }
    };


   /**
      * Generate QR code pictures with logo
      * note The title below the QR code, if it is not necessary to be empty
      * Return the string, put this string into the SRC of the IMG tag
      */
    public static  String drawLogoQRCode(String qrUrl, String logUrl,String note) {
        File logoFile = new File(logUrl);//The absolute path stored by the log. If it is stored under the resource of this project, you can use a certain class. ("/").getPath() to obtain it. If some pictures are stored on the remote server, you can freely modify this line of code.
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // The parameters are: encoding content, encoding type, generating image width, generating image height, setting parameters            BitMatrix bm = (qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            // Start creating Bitmap pictures using QR code data, set to black (0xFFFFFFF) and white (0xFF000000) respectively            for (int x = 0; x &lt; WIDTH; x++) {
                for (int y = 0; y &lt; HEIGHT; y++) {
                    (x, y, (x, y) ? QRCOLOR : BGWHITE);
                }
            }

            int width = ();
            int height = ();
            if ( ()) {
                // Build drawing objects                Graphics2D g = ();
                // Read the logo image                BufferedImage logo = (logoFile);
                // Start drawing logo images                (logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                ();
                ();
            }

            // Custom text description            if ((note)) {
                // For new picture, add text under the QR code with logo                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = ();
                // Draw the QR code to the new panel                (image, 0, 0, (), (), null);
                // Draw text to new panel                ();
                (new Font("Kai Style", , 30)); // Font, font, font size                int strWidth = ().stringWidth(note);
                if (strWidth &gt; 399) {
                    // // If the length is too long, the previous part will be intercepted                    // If the length is too long, the line will be changed                    String note1 = (0, () / 2);
                    String note2 = (() / 2, ());
                    int strWidth1 = ().stringWidth(note1);
                    int strWidth2 = ().stringWidth(note2);
                    (note1, 200 - strWidth1 / 2, height + (() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = ();
                    (outImage, 0, 0, (), (), null);
                    ();
                    (new Font("Songyi", , 30)); // Font, font, font size                    (note2, 200 - strWidth2 / 2,() + (() - ()) / 2 + 5);
                    ();
                    ();
                    outImage = outImage2;
                } else {
                    (note, 200 - strWidth / 2, height + (() - height) / 2 + 12); // Draw text                }
                ();
                ();
                image = outImage;
            }

            ();
            //Write the output stream, used for conversion
            ByteArrayOutputStream tmp = new ByteArrayOutputStream();
            (image, "png", tmp);
            ();
            return "data:image/png;base64,"+(new String(Base64.encodeBase64(())));
        } catch (Exception e) {
            ();
        }
        return null;
    }


  /**
      * Generate QR code pictures without logo
      * note The title below the QR code, if it is not necessary to be empty
      * Return the string, put this string into the SRC of the IMG tag
      */
    public static  String drawLogoQRCodeNotLog(String qrUrl, String note) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // The parameters are: encoding content, encoding type, generating image width, generating image height, setting parameters            BitMatrix bm = (qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            // Start creating Bitmap pictures using QR code data, set to black (0xFFFFFFF) and white (0xFF000000) respectively            for (int x = 0; x &lt; WIDTH; x++) {
                for (int y = 0; y &lt; HEIGHT; y++) {
                    (x, y, (x, y) ? QRCOLOR : BGWHITE);
                }
            }

            int height = ();

            // Custom text description            if ((note)) {
                // For new picture, add text under the QR code with logo                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = ();
                // Draw the QR code to the new panel                (image, 0, 0, (), (), null);
                // Draw text to new panel                ();
                (new Font("Kai Style", , 30)); // Font, font, font size                int strWidth = ().stringWidth(note);
                if (strWidth &gt; 399) {
                    // // If the length is too long, the previous part will be intercepted                    // If the length is too long, the line will be changed                    String note1 = (0, () / 2);
                    String note2 = (() / 2, ());
                    int strWidth1 = ().stringWidth(note1);
                    int strWidth2 = ().stringWidth(note2);
                    (note1, 200 - strWidth1 / 2, height + (() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = ();
                    (outImage, 0, 0, (), (), null);
                    ();
                    (new Font("Songyi", , 30)); // Font, font, font size                    (note2, 200 - strWidth2 / 2,() + (() - ()) / 2 + 5);
                    ();
                    ();
                    outImage = outImage2;
                } else {
                    (note, 200 - strWidth / 2, height + (() - height) / 2 + 12); // Draw text                }
                ();
                ();
                image = outImage;
            }

            ();
            //Write to the cache area for conversion            ByteArrayOutputStream tmp = new ByteArrayOutputStream();
            (image, "png", tmp);
            ();
            return "data:image/png;base64,"+(new String(Base64.encodeBase64(())));
        } catch (Exception e) {
            ();
        }
        return null;
    }

}

 

 

The above two methods are returned strings.Pass this string into the front end and put it in the SRC of the IMG tag!

 

Let's talk about another question:

How to verify the timeliness of a QR code? I will not show the code here, I will only give you a thought:

1. Put the token in the URL that generates the QR code. You can freely use the token value. As long as you can ensure that this token is unique, it is enough.

2. Then save this token toredisIn, set the validity period, such as 60S

3. When the user scans the QR code, he will take the token to jump to the page we specified. At this time, we get the token and pass it to the backend to verify!

 

Click to follow and don’t get lost. Brother Hai teaches you how to learn technology!