Spring Boot整合ZXing实现二维码和条形码生成
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 com.google.zxing.oned.Code128Writer;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class QRCodeAndBarcodeGenerator {
public static void main(String[] args) {
String qrContent = "这是二维码包含的信息";
String barcodeContent = "这是条形码包含的信息";
try {
generateQRCodeImage(qrContent, "qrcode.png");
generateBarcodeImage(barcodeContent, "barcode.png");
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
private static void generateQRCodeImage(String content, String imagePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 500, 500);
Path path = FileSystems.getDefault().getPath(imagePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
private static void generateBarcodeImage(String content, String imagePath) throws IOException, WriterException {
Code128Writer code128Writer = new Code128Writer();
BitMatrix bitMatrix = code128Writer.encode(content, BarcodeFormat.CODE_128, 500, 100);
Path path = FileSystems.getDefault().getPath(imagePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
}
这段代码使用了ZXing库来生成二维码和条形码,并将生成的图像保存到指定的文件路径。在这个例子中,我们创建了两个方法generateQRCodeImage
和generateBarcodeImage
,分别用于生成二维码和条形码图像,并在main方法中调用这两个方法进行测试。
评论已关闭