search
HomeJavajavaTutorialUse Java to generate QR codes with text

Introduction

Mainly uses goole’s zxing package. The sample code is given below, which is very convenient for everyone to understand and learn. The codes are all preliminary frameworks. The functions are available and need to be optimized according to the actual usage. .

First step, maven import zxing

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

Second step, start generating QR code:

private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
/**
 * 把生成的二维码存入到图片中
 * @param matrix zxing包下的二维码类
 * @return
 */
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;
}
/**
 * 生成二维码并写入文件
 * @param content 扫描二维码的内容
 * @param format 图片格式 jpg
 * @param file  文件
 * @throws Exception
 */
public static void writeToFile(String content, String format, File file)
  throws Exception {
 MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
 @SuppressWarnings("rawtypes")
 Map hints = new HashMap();
 //设置UTF-8, 防止中文乱码
 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
 //设置二维码四周白色区域的大小
 hints.put(EncodeHintType.MARGIN,1);
 //设置二维码的容错性
 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
 //画二维码
 BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
 BufferedImage image = toBufferedImage(bitMatrix);
 if (!ImageIO.write(image, format, file)) {
  throw new IOException("Could not write an image of format " + format + " to " + file);
 }
}

The third step, write the text into the QR code image:

/**
 * 给二维码图片加上文字
 * @param pressText 文字
 * @param qrFile  二维码文件
 * @param fontStyle
 * @param color
 * @param fontSize
 */
public static void pressText(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
 pressText = new String(pressText.getBytes(), "utf-8");
 Image src = ImageIO.read(qrFile);
 int imageW = src.getWidth(null);
 int imageH = src.getHeight(null);
 BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
 Graphics g = image.createGraphics();
 g.drawImage(src, 0, 0, imageW, imageH, null);
 //设置画笔的颜色
 g.setColor(color);
 //设置字体
 Font font = new Font("宋体", fontStyle, fontSize);
 FontMetrics metrics = g.getFontMetrics(font);
 //文字在图片中的坐标 这里设置在中间
 int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
 int startY = HEIGHT/2;
 g.setFont(font);
 g.drawString(pressText, startX, startY);
 g.dispose();
 FileOutputStream out = new FileOutputStream(qrFile);
 ImageIO.write(image, "JPEG", out);
 out.close();
 System.out.println("image press success");
}

The fourth step, test it in the main method, a 2D code with text in the middle The code is generated

public static void main(String[] args) throws Exception {
 File qrcFile = new File("/Users/deweixu/","google.jpg");
 writeToFile("www.google.com.hk", "jpg", qrcFile);
 pressText("谷歌", qrcFile, 5, Color.RED, 32);
}

Summary

The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. , if you have any questions, you can leave a message to communicate.

For more articles related to using Java to generate QR codes with text, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools