生成二维码主要代码为在步骤1、2中,下边后续步骤3、4、5涉及到具体的业务。要是用该工具类时需要拷贝前两个步骤代码即可。
1、在项目pom.xml文件中引入生成二维码的第三方依赖
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
2、生成二维码的工具类
public class QRCodeUtils {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
public static void buildQuickMark(String content, String path, String filename) {
try {
BitMatrix byteMatrix = new MultiFormatWriter().encode(new String(content.getBytes(), "iso-8859-1"),
BarcodeFormat.QR_CODE, 300, 300);
String format = Constants.SYS_HOME_QRCODE_FORMAT;
File file = new File(path + "\\" + filename + "." + format);
BufferedImage image = toBufferedImage(byteMatrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
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, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
}
public static void main(String[] args) {
String content = "http://127.0.0.1:8888";
String path = "D:\\QRCode";
String filename = "test";
QRCodeUtils.buildQuickMark(content, path, filename);
System.out.println("创建成功");
}
3、生成的二维码图片
4、生成二维码的业务层代码实现类
@Service
public class SysQRCodeServiceImpl implements SysQRCodeService {
@Autowired
SysConfigService sysConfigService;
public String getQRCode() {
return saveQRCode();
}
public String saveQRCode(){
String configValue = sysConfigService.selectConfigByKey(Constants.SYS_HOME_QRCODE).getConfigValue();
String qrCodeName = "QRCode";
QRCodeUtils.buildQuickMark(configValue,uploadUrl(), qrCodeName);
String resultQRCodeName = qrCodeName+"."+Constants.SYS_HOME_QRCODE_FORMAT;
return resultQRCodeName;
}
public String uploadUrl() {
Date now = new Date();
String date = new SimpleDateFormat("yyyyMM").format(now);
String uploadFilePath = SenseConfig.getUploadFilePath();
File addr = new File(uploadFilePath);
if (!addr.exists()) {
addr.mkdirs();
}
return uploadFilePath;
}
5、生成二维码的业务层代码接口
public interface SysQRCodeService {
String getQRCode();
}
6、生成二维码的接口,共前端调用,获取生成二维码的图片名
@RestController
@RequestMapping("/sys/QRCode")
public class SysQRCodeController {
@Autowired
SysQRCodeService sysQRCodeService;
@RequestMapping()
public AjaxResult getQRCode(){
return AjaxResult.success(sysQRCodeService.getQRCode());
}
}
|