- 存在瓦片:从本地目录读取对应 PNG 文件并返回;
- 瓦片缺失:动态生成一张 256×256 的全透明 PNG 图像,避免前端加载错误;
java
@GetMapping("/tiles/{z}/{x}/{y}.png")
public ResponseEntity<Resource> getTile(
@PathVariable String z,
@PathVariable String x,
@PathVariable String y) throws IOException {
String TILE_ROOT = "";
if ("Windows 10".equals(System.getProperty("os.name"))) {
TILE_ROOT = "本地地址";
} else {
TILE_ROOT = "云端地址/www/java/title/";
}
String path = TILE_ROOT + z + "/" + x + "/" + y + ".png";
File file = new File(path);
if (file.exists()) {
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=\"" + y + ".png\"")
.contentType(MediaType.IMAGE_PNG)
.body(resource);
} else {
// 没有瓦片 → 返回透明图片
byte[] transparentPng = createTransparentPng(256, 256);
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_PNG)
.body(new ByteArrayResource(transparentPng));
}
}
当瓦片不存在时,调用 createTransparentPng(256, 256) 生成一张 256×256 的全透明 PNG:
java
// 创建透明 PNG 的字节数组
private byte[] createTransparentPng(int width, int height) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setColor(new Color(0, 0, 0, 0)); // 全透明
g.fillRect(0, 0, width, height);
g.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
return baos.toByteArray();
}