SpringBoot生成一维码和二维码

时间:2024-04-09 20:10:21
import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; public class BarcodeBase64Converter { public String generateBarcodeBase64(String content, BarcodeFormat format) throws WriterException, IOException { int width = 300; int height = 100; // 生成条形码或二维码 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, format, width, height); // 将码图像写入字节数组输出流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream); // 将字节数组输出流中的数据转换为Base64字符串 byte[] bytes = outputStream.toByteArray(); String base64String = Base64.getEncoder().encodeToString(bytes); return base64String; } public static void main(String[] args) { String barcodeContent = "123456789"; String qrCodeContent = "https://www.example.com"; BarcodeBase64Converter converter = new BarcodeBase64Converter(); try { // 生成一维码 String base64Barcode = converter.generateBarcodeBase64(barcodeContent, BarcodeFormat.CODE_128); System.out.println("Base64 Barcode: " + base64Barcode); // 生成二维码 String base64QRCode = converter.generateBarcodeBase64(qrCodeContent, BarcodeFormat.QR_CODE); System.out.println("Base64 QR Code: " + base64QRCode); } catch (WriterException | IOException e) { e.printStackTrace(); } } }