Spring Boot 实现构建一个轻量级地图瓦片服务

  • 存在瓦片:从本地目录读取对应 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();
}
相关推荐
Selegant5 小时前
Spring Boot 3 + Java 21 全新特性实战:虚拟线程、结构化并发与 Record 类型
java·spring boot·后端
huahailing10245 小时前
springboot 整合 rustfs
spring boot·rustfs
何中应5 小时前
【面试题-6】MySQL
数据库·后端·mysql·面试题
woniu_maggie5 小时前
SAP冲销凭证功能
后端
一念之间lq5 小时前
Elpis 第三阶段· 领域模型架构建设
前端·后端
Jinkxs5 小时前
Java 架构 02:DDD 领域模型设计实战(限界上下文划分)
java·开发语言·架构
+VX:Fegn08955 小时前
计算机毕业设计|基于springboot + vue旅游信息推荐系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计·旅游
百锦再5 小时前
国产数据库的平替亮点——关系型数据库架构适配
android·java·前端·数据库·sql·算法·数据库架构
码界奇点5 小时前
基于SpringBoot和Vue的Fuint门店会员营销系统设计与实现
vue.js·spring boot·后端·毕业设计·springboot·源代码管理