Skip to content

Instantly share code, notes, and snippets.

@leplatrem
Created December 1, 2011 10:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leplatrem/1415795 to your computer and use it in GitHub Desktop.
Save leplatrem/1415795 to your computer and use it in GitHub Desktop.
Tiles serialization in base64 using django and landez
import base64
from StringIO import StringIO
from django.http import HttpResponse
from django.utils import simplejson
from easydict import EasyDict as edict
from landez import TilesManager
from . import app_settings
def tiles_serialize(request):
result = edict(dict(bbox=[-0.56, 44.84, -0.55, 44.85],
zoomlevels=range(17, 19),
mimetype='image/png',
tiles=[]))
# Take tiles from a TMS
tm = TilesManager(tiles_url=app_settings.TILES_URL)
# ... change it to : mb = TilesManager(mbtiles_file="yourfile.mbtiles")
# to take tiles from a MBtiles !
tiles = tm.tileslist(result.bbox, result.zoomlevels)
for tile in tiles:
tm.prepare_tile(tile) # download, extract or take from cache
tile_path = tm.tile_fullpath(tile)
# Encode PNG in base64
output = StringIO()
with open(tile_path) as f:
base64.encode(f, output)
encoded = ''.join(output.getvalue().splitlines())
output.close()
# Add the encoded tile to the list
result.tiles.append(dict(tile=tile,
data=encoded))
# Django specific code to serve the tiles list in JSON
response = HttpResponse(mimetype='application/json')
simplejson.dump(result, response, ensure_ascii=False, separators=(',',':'))
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment