springboot怎么生成条形码
时间: 2023-11-11 10:06:10 浏览: 98
在 Spring Boot 中生成条形码,可以使用第三方库 Zxing。以下是生成条形码的示例代码:
1. 添加依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
```
2. 编写生成条形码的代码
```java
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
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;
@Controller
@RequestMapping("/barcode")
public class BarcodeController {
@GetMapping("/generate")
@ResponseBody
public String generateBarcode(@RequestParam("code") String code) {
try {
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.M);
hints.put(EncodeHintType.MARGIN, 2);
BitMatrix bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.CODE_128, width, height, hints);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
File file = new File("barcode." + format);
ImageIO.write(image, format, file);
return "Barcode generated successfully!";
} catch (WriterException | IOException e) {
e.printStackTrace();
return "Error generating barcode!";
}
}
}
```
3. 测试
启动 Spring Boot 应用,访问 http://localhost:8080/barcode/generate?code=123456,将会在项目根目录下生成名为 barcode.png 的条形码图片。
注意:本示例中生成的是 CODE_128 格式的条形码,你可以根据自己的需求选择不同的格式。
阅读全文