使用Java Spring Boot生成二维码与条形码
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 BarcodeGenerator {
public static void main(String[] args) {
String qrText = "https://www.example.com";
String barcodeText = "123456789012";
try {
generateQRCodeImage(qrText, "qrcode.png");
generateBarcodeImage(barcodeText, "barcode.png");
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
private static void generateQRCodeImage(String text, String imagePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 500, 500);
Path path = FileSystems.getDefault().getPath(imagePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
private static void generateBarcodeImage(String text, String imagePath) throws IOException {
Code128Writer code128Writer = new Code128Writer();
BitMatrix bitMatrix = code128Writer.encode(text, BarcodeFormat.CODE_128, 500, 100);
Path path = FileSystems.getDefault().getPath(imagePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
}
这段代码使用了google zxing
库来生成二维码和条形码。首先,我们创建了一个BarcodeGenerator
类和一个main
方法。在main
方法中,我们定义了要编码的字符串,并调用相应的方法生成二维码和条形码图像。generateQRCodeImage
方法使用QRCodeWriter
来生成二维码,而generateBarcodeImage
方法使用Code128Writer
来生成128编码的条形码。每个方法都捕获了异常,并在必要时打印堆栈跟踪。
评论已关闭