这里是读取切片文件并在您的 WebApi 中提供它们的基本实现。
您需要安装 NuGet System.Data.SQLite.Core(或类似软件)才能访问数据库。
助手类:
public class MbTilesReader
{
private string _mbTilesFilename;
public MbTilesReader(string mbTilesFilename)
{
_mbTilesFilename = mbTilesFilename;
}
public byte[] GetImageData(int x, int y, int zoom)
{
byte[] imageData = null;
using (SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", _mbTilesFilename)))
{
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand(conn))
{
cmd.CommandText = "SELECT * FROM tiles WHERE tile_column = @x and tile_row = @y and zoom_level = @z";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SQLiteParameter("@x", x));
cmd.Parameters.Add(new SQLiteParameter("@y", y));
cmd.Parameters.Add(new SQLiteParameter("@z", zoom));
SQLiteDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
imageData = reader["tile_data"] as byte[];
}
}
}
return imageData;
}
}
然后在您的 ConfigureServices 方法中将该类注册为单例并将路径传递给文件:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new MbTilesReader("c:/temp/map.mbtiles"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
最后,您可以在 WebApi 操作中返回图像,如下所示:
[Route("api/[controller]")]
[ApiController]
public class MapController : ControllerBase
{
private MbTilesReader _tileReader;
public MapController(MbTilesReader tileReader)
{
_tileReader = tileReader;
}
[HttpGet]
public IActionResult Get(int x, int y, int z)
{
byte[] imageData = _tileReader.GetImageData(x, y, z);
return File(imageData, "image/png");
}
}
可能的改进
- 使用缓存避免始终查询相同的图像。
- 使实现异步(请参阅this 问题)。
编辑 - 格式
此答案假设您的数据以 PNG 格式存储,.mbtiles 文件可以以以下格式存储数据 pbf(用于矢量)、jpg、png 和 webapp。要了解您的数据库使用的是哪种格式,请检查 .mbtiles SQLite 数据库的表元数据中的数据。
查看以下链接了解更多信息:https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md