前言:
需求:生成二维码/条形码
//使用ZXing库
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
示例代码:
生成二维码
public class QRCodeGeneratorService {
/**
* 生成QR码的方法
* @param data 二维码内容
* @param width 二维码宽度
* @param height 二维码高度
* @param filePath 生成路径
*/
public void generateQRCode(String data, int width, int height, String filePath) {
try {
Map<EncodeHintType, Object> hints = new HashMap<>(3);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 错误纠正级别
hints.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H);
// 二维码边距
hints.put(EncodeHintType.MARGIN, 1);
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.QR_CODE, width, height, hints);
// 创建BufferedImage对象来表示QR码
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, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
}
}
// 将QR码保存到文件
File qrCodeFile = new File(filePath);
ImageIO.write(image, "png", qrCodeFile);
System.out.println("QR码已生成并保存到: " + filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
QRCodeGeneratorService qrCodeGenerator = new QRCodeGeneratorService();
// 要存储在QR码中的数据
String data = "https://www.baidu.com/";
// QR码的宽度
int width = 300;
// QR码的高度
int height = 300;
// 生成的QR码文件的路径
String filePath = "qrcode.png";
qrCodeGenerator.generateQRCode(data, width, height, filePath);
}
}
生成条形码
public class BarcodeGeneratorService {
/**
* 生成条形码的方法
* @param data 条形码内容
* @param width 条形码宽度
* @param height 条形码高度
* @param filePath 生成路径
*/
public void generateBarcode(String data, int width, int height, String filePath) {
try {
Map<EncodeHintType, Object> hints = new HashMap<>(2);
// 设置字符编码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.CODE_128, width, height, hints);
// 创建BufferedImage对象来表示条形码
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, bitMatrix.get(x, y) ? 0 : 0xFFFFFF);
}
}
// 将条形码保存到文件
File barcodeFile = new File(filePath);
ImageIO.write(image, "png", barcodeFile);
System.out.println("条形码已生成并保存到: " + filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
BarcodeGeneratorService barcodeGenerator = new BarcodeGeneratorService();
// 要存储在条形码中的数据
String data = "123456789";
// 条形码的宽度
int width = 200;
// 条形码的高度
int height = 100;
// 生成的条形码文件的路径
String filePath = "barcode.png";
barcodeGenerator.generateBarcode(data, width, height, filePath);
}
}
标签:条形码,java,filePath,int,height,width,二维码,new From: https://www.cnblogs.com/Kikai/p/17863713.html