Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to synthesize complex QR Code Pictures by java zxing

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the knowledge of "how to synthesize complex QR code pictures by java zxing". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Overall thinking:

The mature QR code generation interface of zxing is introduced to generate the standard QR code file. The relevant text description is added to the QR code through java graphics and image processing API. According to the need, the relevant background can be added to the synthesized picture. Examples are shown in the following figure:

1. Take the point bitmap as an example, the core code for generating the QR code picture is as follows

/ * define the parameter of the QR code * / HashMap hints = new HashMap (); / / specify the character encoding as "utf-8" hints.put (EncodeHintType.CHARACTER_SET, "utf-8"); / / specify the error correction level of the QR code as intermediate hints.put (EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H) / / set the margin of the picture hints.put (EncodeHintType.MARGIN, 1); / * generate the QR code * / try {BitMatrix bitMatrix = new MultiFormatWriter (). Encode (content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT, hints); Path file = new File (filePath). ToPath (); MatrixToImageWriter.writeToPath (bitMatrix, format, file) } catch (Exception e) {log.error ("error in QR code generation: / permitDownload: error", e);}

two。 Add text to the QR code

/ * * add description text * * @ param image original QR code * @ param topText top description text * @ param downText bottom description text * @ return QR code with description text * / private static BufferedImage addNote (BufferedImage image, String topText, String downText) {Image src = image.getScaledInstance (QRCODE_WIDTH, QRCODE_HEIGHT, Image.SCALE_DEFAULT) BufferedImage tag = new BufferedImage (QRCODE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D G2 = tag.createGraphics (); / / set the text g2.setColor (Color.BLACK); g2.setBackground (Color.WHITE); g2.clearRect (0CodeWIDTH, IMAGE_HEIGHT) / / set the top text and calculate the coordinates / / ensure that the operating system contains the "Arial" font. If the font is not uploaded to JAVA_HOME/jre/lib/fonts, FontMetrics fm = getFontByWidth (new Font ("Arial", Font.PLAIN, DEFAULT_FONT_SIZE), topText, G2); / / the width of the text int fontWidth = fm.stringWidth (topText) / / text height int fontHeight = fm.getHeight (); / * * add text to the top and center * / g2.drawString (topText, (QRCODE_WIDTH-fontWidth) / 2, (TEXT_DEFAULT_HEIGHT-fontHeight) / 2 + fm.getFont () .getSize ()) / * draw QR code * / g2.drawImage (src, 0, TEXT_DEFAULT_HEIGHT, null) / / set the bottom text font and calculate the coordinates / / ensure that the operating system contains the "Verdana" font. If the font is not uploaded to JAVA_HOME/jre/lib/fonts, fm = getFontByWidth (new Font ("Arial", Font.PLAIN, DEFAULT_FONT_SIZE), downText, G2); / / the width of the text fontWidth = fm.stringWidth (downText) / / text height fontHeight = fm.getHeight (); / * add bottom text * / g2.drawString (downText, (QRCODE_WIDTH-fontWidth) / 2, QRCODE_HEIGHT + TEXT_DEFAULT_HEIGHT+ (TEXT_DEFAULT_HEIGHT-fontHeight) / 2 + fm.getFont (). GetSize ()); g2.dispose (); image = tag Image.flush (); return image;}

Knowledge: the length of the text at the bottom will change. At present, there is only one line of text in the design, so according to the number of words, the text size will be dynamically changed in a reasonable range (not too small to be recognized). Using the FontMetrics object will be helpful to most students.

3. Dynamically modify font and size

/ * * change text size according to text length * * @ param font default font * @ param note text content * @ param G2 image canvas * @ return processed font encapsulation * / private static FontMetrics getFontByWidth (Font font, String note, Graphics2D G2) {FontMetrics fm = g2.getFontMetrics (font); int textWidth = fm.stringWidth (note) / / if (textWidth > QRCODE_WIDTH) {int fontSize = (int) ((TEMP_PARAM / textWidth) * font.getSize ()); font = new Font (font.getName (), font.getStyle (), fontSize);} g2.setFont (font); return g2.getFontMetrics (font);}

4. The last step is to combine the blue background with the QR code image.

Picture synthesis quadrilogy

Step 1: to create a canvas, you need to set the width and height of the canvas in pixels

BufferedImage tag = new BufferedImage (QRCODE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB)

Step 2: create a graphic object Graphics2D on the canvas, which can be set according to your knowledge of the image, such as background, foreground, border, width and so on.

Graphics2D G2 = tag.createGraphics (); / / set text

Step 3: synthesize the picture. The order, size and coordinate position of the picture will affect the final rendering effect. If the final effect does not meet the design requirements, it will be helpful to adjust these three parameters.

Image src = image.getScaledInstance (QRCODE_WIDTH, QRCODE_HEIGHT, Image.SCALE_DEFAULT);. / * draw QR code * / g2.drawImage (src, 0, TEXT_DEFAULT_HEIGHT, null)

Step 4: generate the final new picture

/ * add background image to QR code image * * @ param qrPic code * @ param backImage background picture * / private static void createNewPng (File qrPic, BufferedImage backImage) {try {if (! qrPic.isFile ()) {log.error ("temporary path of QR code does not exist!") ;} / * read the background picture and build the drawing object-canvas * / Graphics2D g = backImage.createGraphics (); / * * read QR code picture * / BufferedImage qrcodeImage = ImageIO.read (qrPic) / / start drawing g.drawImage (qrcodeImage, 48,120, qrcodeImage.getWidth (), qrcodeImage.getHeight (), null); g.dispose (); ImageIO.write (backImage, "png", qrPic);} catch (Exception e) {log.error ("error drawing QR code!") ;}}

The second picture is generated by the same process as the first picture, except that the text [2. Add text to the QR code] change the order from top, middle and bottom to left and right.

Stepped on the pit

The pixel and size of the background picture need to match the QR code, otherwise there will be a serious imbalance between the QR code and the background or the incomplete display of the QR code.

Add text garbled to the QR code development environment (windows), test environment (centos server version). There is no problem with the local development test. After being packaged and deployed to the server, all Chinese characters appear garbled (various transcodes, font settings, debugging for a long time), and the problem remains unchanged. In the end, Lingguang suspected that it was the font problem of the system. I checked that the font information in the test environment (centos) really did not have "Arial style" and was set to the system's own or default font. The problem remained. Finally, restart the application from the copy font in the development system (c:\ windows\ fonts\ simsun.ttc) to the test system (JAVA_HOME/jre/libs/fonts), and the problem is solved perfectly. System installation and deployment need to prepare fonts is a bit troublesome, I do not know if there is a better way, fonts have logical fonts and physical fonts, love, let's do this first.

The background image loading problem project is the springboot project, and the background image is stored in the resources folder. There is no exception in the local development test. The background image cannot be found after being packaged and deployed to the server. The original code is as follows

String backFilePath = "template/down.png"; ClassPathResource resource = new ClassPathResource (backFilePath); File file = resource.getFile ()

The method of finding and loading pictures on the Internet has been used, but has no effect, and finally modified to the input stream, the picture synthesis is normal, the code is as follows

/ * background image information cannot be obtained by different operating systems * / String backFilePath = "template/down.png"; ClassPathResource resource = new ClassPathResource (backFilePath); BufferedImage bi = ImageIO.read (resource.getInputStream ()); "how to synthesize complex QR code images" is introduced here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report