Java二维码与条形码生成库详解:ZXing、QRGen与Barcode4J实战代码示例
import com.google.zxing.BarcodeFormat;
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 java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class QRCodeGenerator {
public static void main(String[] args) {
String text = "Hello, World!";
int width = 200;
int height = 200;
String filePath = "./generated_qrcode.png";
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
System.out.println("QR Code generated successfully at " + filePath);
} catch (WriterException | IOException e) {
System.out.println("Error generating QR Code: " + e.getMessage());
}
}
}
这段代码使用了ZXing库来生成一个二维码图像,并将其保存到指定路径。首先创建了一个QRCodeWriter
对象,然后调用encode
方法生成二维码的位矩阵BitMatrix
,最后使用MatrixToImageWriter.writeToPath
方法将位矩阵转换为图像并保存到文件系统。
评论已关闭