一:导包
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
二:配置
2.1 配置application.yaml
barcode:
path: http://192.168.0.109:8080/
2.2 读取配置
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(
prefix = "barcode"
)
public class BarcodeConfig {
private String path;
}
三 封装工具
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
public class BarcodeUtil {
/**
* 生成条形二维码并转换为 Base64 字符串
* @param path 访问全路径
* @throws WriterException
* @throws IOException
*/
public static String getBarcode(String path) throws WriterException, IOException {
int width = 300;
int height = 150;
BitMatrix bitMatrix = new MultiFormatWriter().encode(path, BarcodeFormat.CODE_128, width, height);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
//将二维码图像转换为Base64字符串
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
String barcodeImage = Base64.getEncoder().encodeToString(imageBytes);
String string = "data:image/png;base64," + barcodeImage;
return string;
}
/**
* 生成二维码并转换为 Base64 字符串
* @param path 访问全路径
* @throws WriterException
* @throws IOException
*/
public static String getQRCode(String path) throws WriterException, IOException {
int width = 300; //二维码的宽度
int height = 300; //二维码的高度,通常二维码是正方形的
//使用QRCodeWriter生成二维码
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(path, BarcodeFormat.QR_CODE, width, height);
//将二维码图像转换为BufferedImage
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
//将二维码图像转换为Base64字符串
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
String barcodeImage = Base64.getEncoder().encodeToString(imageBytes);
String string = "data:image/png;base64," + barcodeImage;
return string;
}
}
四 逻辑使用
@Autowired
private BarcodeConfig barcodeConfig;
public void test() {
String id = "123123";
try {
System.out.println(BarcodeUtil.getQRCode(barcodeConfig.getPath() + "?id=" + id));
} catch (Exception e) {
throw new RuntimeException(e);
}
}