本文主要是介绍ZXing生成二维码与条形码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、添加ZXing依赖
<dependencies><!-- 其他依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.4.1</version></dependency>
</dependencies>
2.生成二维码
public void generateQRCode(String data, int width, int height, String filePath) {try {Map<EncodeHintType, Object> hints = new HashMap<>();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();String data = "https://www.baidu.com/"; // 要存储在QR码中的数据int width = 300; // QR码的宽度int height = 300; // QR码的高度String filePath = "D:/qrcode.png"; // 生成的QR码文件的路径qrCodeGenerator.generateQRCode(data, width, height, filePath);
}
3.生成条形码
public void generateBarcode(String data, int width, int height, String filePath) {try {Map<EncodeHintType, Object> hints = new HashMap<>();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 = "D:/barcode.png"; // 生成的条形码文件的路径barcodeGenerator.generateBarcode(data, width, height, filePath);}
这篇关于ZXing生成二维码与条形码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!