java生成二维码

本文介绍了一种使用Java实现将文字信息转换为二维码的方法。通过使用Google ZXing库,包括MultiFormatWriter和MatrixToImageWriter类,可以创建指定大小的二维码,并将其保存为GIF格式的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.ce.erweima.demo;

import java.io.File;
import java.util.Hashtable;

import com.ce.erweima.util.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
/**
 * 将文字转换成二维码
 */
public class Encoder {
	public static void main(String[] args) throws Exception {
		String text = "https://blog.youkuaiyun.com/qq_20124743/article/details/78905220";
		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, 300, 300, hints);
		MatrixToImageWriter.writeToFile(bitMatrix, "gif", new File("D:/aa.gif"));
		System.out.println("二维码生成完成");
	}
}

util类
package com.ce.erweima.util;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;
public final class MatrixToImageWriter {
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	private MatrixToImageWriter() {
	}
	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;
	}
	public static void writeToFile(BitMatrix matrix, String format, File file)
			throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, file)) {
			throw new IOException("Could not write an image of format "
					+ format + " to " + file);
		}
	}
	public static void writeToStream(BitMatrix matrix, String format,
			OutputStream stream) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format "
					+ format);
		}
	}
}

 

使用到的jar包   core.jar    javase.jar

### 使用 Java 生成二维码 (QR Code)Java生成二维码,最常用的方法是使用 **ZXing**(Zebra Crossing)库。ZXing 是一个开源的、跨平台的条形码和二维码生成与解析库,支持多种编码格式和纠错机制。 #### 1. Maven 依赖配置 首先,在 `pom.xml` 文件中添加 ZXing 的依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.5.2</version> </dependency> ``` #### 2. 生成二维码的核心代码 以下是一个简单的 Java 示例,展示如何使用 ZXing 生成二维码并将其保存为图像文件: ```java import com.google.zxing.*; 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 java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; public class QRCodeGenerator { public static void generateQRCode(String data, String filePath, int width, int height) throws WriterException, IOException { // 设置二维码的纠错级别 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height, com.google.zxing.EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 写入文件 Path path = FileSystems.getDefault().getPath(filePath); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); } public static void main(String[] args) { String data = "https://www.example.com"; String filePath = "qrcode.png"; int width = 300; int height = 300; try { generateQRCode(data, filePath, width, height); System.out.println("二维码生成成功!"); } catch (Exception e) { System.err.println("生成二维码失败:" + e.getMessage()); } } } ``` #### 3. 自定义二维码(添加 Logo) 如果希望在二维码中心添加 Logo,可以在生成二维码图像后,使用 `BufferedImage` 和 `Graphics2D` 将 Logo 叠加到二维码图像上: ```java import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; public class QRCodeWithLogo { public static void addLogoToQRCode(String qrCodePath, String logoPath, String outputFilePath, int logoSize) throws Exception { BufferedImage qrImage = ImageIO.read(new File(qrCodePath)); BufferedImage logo = ImageIO.read(new File(logoPath)); // 调整 Logo 大小 Image scaledLogo = logo.getScaledInstance(logoSize, logoSize, Image.SCALE_SMOOTH); BufferedImage resizedLogo = new BufferedImage(logoSize, logoSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g = resizedLogo.createGraphics(); g.drawImage(scaledLogo, 0, 0, null); g.dispose(); // 在二维码中心绘制 Logo Graphics2D graphics = qrImage.createGraphics(); int x = (qrImage.getWidth() - logoSize) / 2; int y = (qrImage.getHeight() - logoSize) / 2; graphics.drawImage(resizedLogo, x, y, null); graphics.dispose(); // 保存结果 ImageIO.write(qrImage, "PNG", new File(outputFilePath)); } public static void main(String[] args) throws Exception { String qrCodePath = "qrcode.png"; String logoPath = "logo.png"; String outputFilePath = "qrcode_with_logo.png"; int logoSize = 50; addLogoToQRCode(qrCodePath, logoPath, outputFilePath, logoSize); System.out.println("二维码添加 Logo 成功!"); } } ``` #### 4. 常见问题处理 在使用 ZXing 生成二维码时,可能会遇到如下异常: - **`data bits cannot fit in the QR Code`**:表示数据量超出了当前版本二维码的容量限制。可以通过提高二维码的版本(`Version`)或降低数据量来解决。例如,使用 `EncodeHintType.QR_VERSION` 设置更高的版本[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值