springboot怎么生成条形码并传输给前端
时间: 2023-08-10 21:09:34 浏览: 264
可以使用zxing库生成条形码,并将生成的条形码转换为Base64编码格式传输给前端。
首先在pom.xml中引入zxing库:
```
<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>
```
然后编写生成条形码的代码:
```
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.tomcat.util.codec.binary.Base64;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class BarCodeUtil {
public static String generateBarCode(String contents) throws WriterException, IOException {
int width = 200; // 条形码宽度
int height = 50; // 条形码高度
String format = "png"; // 条形码图片格式
// 定义条形码参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码方式
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错等级
hints.put(EncodeHintType.MARGIN, 2); // 边框宽度
// 生成条形码
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, width, height, hints);
// 将BitMatrix转换为ByteArrayOutputStream
ByteArrayOutputStream out = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, format, out);
// 将ByteArrayOutputStream转换为Base64编码格式
byte[] bytes = out.toByteArray();
String base64Img = Base64.encodeBase64String(bytes);
return base64Img;
}
}
```
最后在Controller中调用该方法,并将返回的Base64编码格式的条形码传输给前端:
```
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class BarCodeController {
@GetMapping("/barCode")
public String generateBarCode(Model model) throws WriterException, IOException {
String contents = "123456789"; // 条形码内容
String image = BarCodeUtil.generateBarCode(contents);
model.addAttribute("image", image);
return "barCode";
}
}
```
在前端页面中显示条形码:
```
<img src="data:image/png;base64,${image}" />
```
阅读全文