Extract images from an MBTiles file (or, getting actual tiles from TileMill)

Hello from the future! If you landed on this post from Google, you should probably check out MBUtil. If that doesn’t do what you want, then maybe come back here.

I was trying to adapt an existing project to Devseed’s shiny new TileMill tool. TileMill is easily the shortest path yet from data to map (assuming the data is already in a supported spatial format, and you’re interested in designing your map using a CSS-like language), and it’ll be exciting to see it evolve. If you make maps for the web, take a look.

The export format TileMill uses (MBTile) threw me for a loop, though: I hadn’t encountered it before. What I wanted was the standard set of nested folders of PNG files. A .mbtiles file is actually an SQLite database, with the tiles (and more metadata) stored inside.

mbutil’ looked promising, but I couldn’t get it to build. What to do?

Well— it’s just Sqlite. Assuming that they didn’t do anything strange while stuffing the tile data into the database, it shouldn’t be too hard to extract them. I could have (and perhaps should have) read the MBTiles specification at this point, but decided to try just poking around.

What I found was, a “tiles” table, which stored a row for each tile, including zoom level, row, column, and the actual binary PNG data. Score!

From there, it wasn’t too hard to throw together a one-off Python script to extract the images. If I was more motivated, it wouldn’t be a stretch to make this a little more general purpose and reusable.