'k': 1.0, 'units': 'm', 'nadgrids': '@null', 'no_defs': True } gym = pyproj.Proj(srs) northwest = map.pointLocation(ModestMaps.Core.Point(0, 0)) southeast = map.pointLocation(dimensions) left, top = gym(northwest.lon, northwest.lat) right, bottom = gym(southeast.lon, southeast.lat) map = mapnik.Map(dimensions.x, dimensions.y) mapnik.load_map(map, stylesheet) map.zoom_to_box(mapnik.Envelope(left, top, right, bottom)) img = mapnik.Image(dimensions.x, dimensions.y) mapnik.render(map, img) img = PIL.Image.fromstring('RGBA', (dimensions.x, dimensions.y), img.tostring()) if format == '.jpg': img.save(output, quality=85) else: img.save(output) ########NEW FILE########
def do_encoding(): image = None results = {} sortable = {} def run(func, im, format, t): global image image = im start = time.time() set = t.repeat(iterations, 1) elapsed = (time.time() - start) min_ = min(set) * 1000 avg = (sum(set) / len(set)) * 1000 name = func.__name__ + ' ' + format results[name] = [min_, avg, elapsed * 1000, name, len(func())] sortable[name] = [min_] if 'blank' in tiles: def blank(): return eval('image.tostring("%s")' % c) blank_im = mapnik.Image(512, 512) for c in combinations: t = Timer(blank) run(blank, blank_im, c, t) if 'solid' in tiles: def solid(): return eval('image.tostring("%s")' % c) solid_im = mapnik.Image(512, 512) solid_im.background = mapnik.Color("#f2efe9") for c in combinations: t = Timer(solid) run(solid, solid_im, c, t) if 'many_colors' in tiles: def many_colors(): return eval('image.tostring("%s")' % c) # lots of colors: http://tile.osm.org/13/4194/2747.png many_colors_im = mapnik.Image.open('../data/images/13_4194_2747.png') for c in combinations: t = Timer(many_colors) run(many_colors, many_colors_im, c, t) if 'aerial_24' in tiles: def aerial_24(): return eval('image.tostring("%s")' % c) aerial_24_im = mapnik.Image.open('../data/images/12_654_1580.png') for c in combinations: t = Timer(aerial_24) run(aerial_24, aerial_24_im, c, t) for key, value in sorted(sortable.iteritems(), key=lambda (k, v): (v, k)): s = results[key] min_ = str(s[0])[:6] avg = str(s[1])[:6] elapsed = str(s[2])[:6] percent_reduction = s[4] name = s[3] size = s[4] print 'min: %sms | avg: %sms | total: %sms | len: %s <-- %s' % ( min_, avg, elapsed, size, name)
def tile(request, version, rasterlayer_id, zoom, x, y): try: rasterlayer = RasterLayer.objects.get(id=rasterlayer_id) if version != "1.0": raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) * TILE_WIDTH yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT minLong = x * xExtent - 20026376.39 minLat = y * yExtent - 20026376.39 maxLong = minLong + xExtent maxLat = minLat + yExtent map = mapnik.Map( TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +units=m +k=1.0 +nadgrids=@null +no_defs" ) map.background = mapnik.Color("#00000000") raster = mapnik.Layer("raster") raster.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" # se carga el archivo file_path = rasterlayer.file_path file_name = rasterlayer.file_name file_format = rasterlayer.file_format ext = file_format file_name = file_name.replace(ext, "-proj" + ext) fullName = join(file_path, file_name) numBands = rasterlayer.numBands # se obtiene el estilo layer_styles = Style.objects.filter(layers__id=rasterlayer.id) if numBands == 1 and layer_styles.count() == 1: raster.datasource = mapnik.Gdal(file=fullName, band=1) else: raster.datasource = mapnik.Gdal(file=fullName) style = mapnik.Style() rule = mapnik.Rule() symbol = mapnik.RasterSymbolizer() # agregar estilo si existe if layer_styles.count() == 1: layer_style = layer_styles[0] colorMap = getColorMap(layer_style) c = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color(0, 0, 0, 0)) for entry in colorMap: color = entry["color"] quantity = entry["quantity"] c.add_stop(quantity, mapnik.Color(color)) symbol.colorizer = c rule.symbols.append(symbol) style.rules.append(rule) map.append_style("estilo", style) raster.styles.append("estilo") map.layers.append(raster) map.zoom_to_box(mapnik.Box2d(minLong, minLat, maxLong, maxLat)) image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT) mapnik.render(map, image) imageData = image.tostring('png') return HttpResponse(imageData, content_type="image/png") except: traceback.print_exc() return HttpResponse("Error")
def render_with_agg(self, m, size): # Render image with default Agg renderer im = mapnik.Image(size, size) mapnik.render(m, im) return im
def generate_geometric_image(self, geometry): spatial_references = { 3857: "+init=epsg:3857", # font: https://help.openstreetmap.org/questions/13250/what-is-the-correct-projection-i-should-use-with-mapnik 4326: "+init=epsg:4326", 4674: "+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs ", 4618: "+proj=longlat +ellps=aust_SA +towgs84=-67.35,3.88,-38.22,0,0,0,0 +no_defs", 9999: "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs" } map = mapnik.Map(800, 600) ds = mapnik.CSV(inline='wkt\n"' + geometry.wkt + '"', filesize_max=500) layer = mapnik.Layer('world') map.background = mapnik.Color('white') # steelblue white geom_type = self.define_geometry_type(geometry) if geom_type not in ['polygon', 'multipolygon']: mapnik.load_map(map, 'style.xml') layer.srs = spatial_references[geometry.srs.srid] # object.wkt.srs layer.datasource = ds layer.styles.append(geom_type) map.layers.append(layer) map.zoom_all() image = mapnik.Image(800, 600) mapnik.render(map, image) image.save('geometry.png') with open('geometry.png', 'rb') as geometry_png: data = geometry_png.read() os.remove('geometry.png') return data style = mapnik.Style() rule = mapnik.Rule() polygon_symbolizer = mapnik.PolygonSymbolizer() polygon_symbolizer.fill = mapnik.Color('#33AA33') #('#f2eff9') rule.symbols.append(polygon_symbolizer) line_symbolizer = mapnik.LineSymbolizer() line_symbolizer.stroke = mapnik.Color('rgb(90%,90%,90%)') line_symbolizer.stroke_width = 0.1 rule.symbols.append(line_symbolizer) #point_symbolizer = mapnik.PointSymbolizer()#"marker-icon.png") #point_symbolizer.file = "marker-icon.png" #point_symbolizer.allow_overlap = True #rule.symbols.append(point_symbolizer) style.rules.append(rule) map.append_style('style', style) layer.srs = spatial_references[geometry.srs.srid] # object.wkt.srs layer.datasource = ds layer.styles.append('style') map.layers.append(layer) map.zoom_all() mapnik.render_to_file(map, 'geometry.png', 'png') with open('geometry.png', 'rb') as geometry_png: data = geometry_png.read() os.remove('geometry.png') return data
def test_negative_image_dimensions(): # TODO - this may have regressed in https://github.com/mapnik/mapnik/commit/4f3521ac24b61fc8ae8fd344a16dc3a5fdf15af7 im = mapnik.Image(-40,40)
def test_quality_threshold_invalid2(): im = mapnik.Image(256, 256) im.tostring('webp:quality=-1')
def _test_dataraster_16bsi_rendering(lbl, overview, rescale, clip): if rescale: lbl += ' Sc' if clip: lbl += ' Cl' ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table='"dataRaster"', band=1, use_overviews=1 if overview else 0, prescale_rasters=rescale, clip_rasters=clip) fs = ds.featureset() feature = fs.next() eq_(feature['rid'], 1) lyr = mapnik.Layer('dataraster_16bsi') lyr.datasource = ds expenv = mapnik.Box2d(-14637, 3903178, 1126863, 4859678) env = lyr.envelope() # As the input size is a prime number both horizontally # and vertically, we expect the extent of the overview # tables to be a pixel wider than the original, whereas # the pixel size in geographical units depends on the # overview factor. So we start with the original pixel size # as base scale and multiply by the overview factor. # NOTE: the overview table extent only grows north and east pixsize = 500 # see gdalinfo dataraster.tif tol = pixsize * max(overview.split(',')) if overview else 0 assert_almost_equal(env.minx, expenv.minx) assert_almost_equal(env.miny, expenv.miny, delta=tol) assert_almost_equal(env.maxx, expenv.maxx, delta=tol) assert_almost_equal(env.maxy, expenv.maxy) mm = mapnik.Map(256, 256) style = mapnik.Style() col = mapnik.RasterColorizer() col.default_mode = mapnik.COLORIZER_DISCRETE col.add_stop(0, mapnik.Color(0x40, 0x40, 0x40, 255)) col.add_stop(10, mapnik.Color(0x80, 0x80, 0x80, 255)) col.add_stop(20, mapnik.Color(0xa0, 0xa0, 0xa0, 255)) sym = mapnik.RasterSymbolizer() sym.colorizer = col rule = mapnik.Rule() rule.symbols.append(sym) style.rules.append(rule) mm.append_style('foo', style) lyr.styles.append('foo') mm.layers.append(lyr) mm.zoom_to_box(expenv) im = mapnik.Image(mm.width, mm.height) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:full') # no data eq_(im.view(1, 1, 1, 1).tostring(), '\x00\x00\x00\x00') eq_(im.view(255, 255, 1, 1).tostring(), '\x00\x00\x00\x00') eq_(im.view(195, 116, 1, 1).tostring(), '\x00\x00\x00\x00') # A0A0A0 eq_(im.view(100, 120, 1, 1).tostring(), '\xa0\xa0\xa0\xff') eq_(im.view(75, 80, 1, 1).tostring(), '\xa0\xa0\xa0\xff') # 808080 eq_(im.view(74, 170, 1, 1).tostring(), '\x80\x80\x80\xff') eq_(im.view(30, 50, 1, 1).tostring(), '\x80\x80\x80\xff') # 404040 eq_(im.view(190, 70, 1, 1).tostring(), '\x40\x40\x40\xff') eq_(im.view(140, 170, 1, 1).tostring(), '\x40\x40\x40\xff') # Now zoom over a portion of the env (1/10) newenv = mapnik.Box2d(273663, 4024478, 330738, 4072303) mm.zoom_to_box(newenv) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10') # nodata eq_(hexlify(im.view(255, 255, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(200, 254, 1, 1).tostring()), '00000000') # A0A0A0 eq_(hexlify(im.view(90, 232, 1, 1).tostring()), 'a0a0a0ff') eq_(hexlify(im.view(96, 245, 1, 1).tostring()), 'a0a0a0ff') # 808080 eq_(hexlify(im.view(1, 1, 1, 1).tostring()), '808080ff') eq_(hexlify(im.view(128, 128, 1, 1).tostring()), '808080ff') # 404040 eq_(hexlify(im.view(255, 0, 1, 1).tostring()), '404040ff')
def _test_rgba_8bui_rendering(lbl, overview, rescale, clip): if rescale: lbl += ' Sc' if clip: lbl += ' Cl' ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table='(select * from "River") foo', use_overviews=1 if overview else 0, prescale_rasters=rescale, clip_rasters=clip) fs = ds.featureset() feature = fs.next() eq_(feature['rid'], 1) lyr = mapnik.Layer('rgba_8bui') lyr.datasource = ds expenv = mapnik.Box2d(0, -210, 256, 0) env = lyr.envelope() # As the input size is a prime number both horizontally # and vertically, we expect the extent of the overview # tables to be a pixel wider than the original, whereas # the pixel size in geographical units depends on the # overview factor. So we start with the original pixel size # as base scale and multiply by the overview factor. # NOTE: the overview table extent only grows north and east pixsize = 1 # see gdalinfo river.tif tol = pixsize * max(overview.split(',')) if overview else 0 assert_almost_equal(env.minx, expenv.minx) assert_almost_equal(env.miny, expenv.miny, delta=tol) assert_almost_equal(env.maxx, expenv.maxx, delta=tol) assert_almost_equal(env.maxy, expenv.maxy) mm = mapnik.Map(256, 256) style = mapnik.Style() sym = mapnik.RasterSymbolizer() rule = mapnik.Rule() rule.symbols.append(sym) style.rules.append(rule) mm.append_style('foo', style) lyr.styles.append('foo') mm.layers.append(lyr) mm.zoom_to_box(expenv) im = mapnik.Image(mm.width, mm.height) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:full') #im.save('/tmp/xfull.png') # for debugging # no data eq_(hexlify(im.view(3, 3, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(250, 250, 1, 1).tostring()), '00000000') # full opaque river color eq_(hexlify(im.view(175, 118, 1, 1).tostring()), 'b9d8f8ff') # half-transparent pixel pxstr = hexlify(im.view(122, 138, 1, 1).tostring()) apat = ".*(..)$" match = re.match(apat, pxstr) assert match, 'pixel ' + pxstr + ' does not match pattern ' + apat alpha = match.group(1) assert alpha != 'ff' and alpha != '00', \ 'unexpected full transparent/opaque pixel: ' + alpha # Now zoom over a portion of the env (1/10) newenv = mapnik.Box2d(166, -105, 191, -77) mm.zoom_to_box(newenv) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10') #im.save('/tmp/xtenth.png') # for debugging # no data eq_(hexlify(im.view(255, 255, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(200, 40, 1, 1).tostring()), '00000000') # full opaque river color eq_(hexlify(im.view(100, 168, 1, 1).tostring()), 'b9d8f8ff') # half-transparent pixel pxstr = hexlify(im.view(122, 138, 1, 1).tostring()) apat = ".*(..)$" match = re.match(apat, pxstr) assert match, 'pixel ' + pxstr + ' does not match pattern ' + apat alpha = match.group(1) assert alpha != 'ff' and alpha != '00', \ 'unexpected full transparent/opaque pixel: ' + alpha
def test_transparency_levels(): # create partial transparency image im = mapnik.Image(256, 256) im.background = mapnik.Color('rgba(255,255,255,.5)') c2 = mapnik.Color('rgba(255,255,0,.2)') c3 = mapnik.Color('rgb(0,255,255)') for y in range(0, im.height() / 2): for x in range(0, im.width() / 2): im.set_pixel(x, y, c2) for y in range(im.height() / 2, im.height()): for x in range(im.width() / 2, im.width()): im.set_pixel(x, y, c3) t0 = tmp_dir + 'white0.png' t2 = tmp_dir + 'white2.png' t1 = tmp_dir + 'white1.png' # octree format = 'png8:m=o:t=0' im.save(t0, format) im_in = mapnik.Image.open(t0) t0_len = len(im_in.tostring(format)) eq_( t0_len, len( mapnik.Image.open('images/support/transparency/white0.png'). tostring(format))) format = 'png8:m=o:t=1' im.save(t1, format) im_in = mapnik.Image.open(t1) t1_len = len(im_in.tostring(format)) eq_( len(im.tostring(format)), len( mapnik.Image.open('images/support/transparency/white1.png'). tostring(format))) format = 'png8:m=o:t=2' im.save(t2, format) im_in = mapnik.Image.open(t2) t2_len = len(im_in.tostring(format)) eq_( len(im.tostring(format)), len( mapnik.Image.open('images/support/transparency/white2.png'). tostring(format))) eq_(t0_len < t1_len < t2_len, True) # hextree format = 'png8:m=h:t=0' im.save(t0, format) im_in = mapnik.Image.open(t0) t0_len = len(im_in.tostring(format)) eq_( t0_len, len( mapnik.Image.open('images/support/transparency/white0.png'). tostring(format))) format = 'png8:m=h:t=1' im.save(t1, format) im_in = mapnik.Image.open(t1) t1_len = len(im_in.tostring(format)) eq_( len(im.tostring(format)), len( mapnik.Image.open('images/support/transparency/white1.png'). tostring(format))) format = 'png8:m=h:t=2' im.save(t2, format) im_in = mapnik.Image.open(t2) t2_len = len(im_in.tostring(format)) eq_( len(im.tostring(format)), len( mapnik.Image.open('images/support/transparency/white2.png'). tostring(format))) eq_(t0_len < t1_len < t2_len, True)
# the bounding box to mercator to properly position # the Map when we call `zoom_to_box()` transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) # Mapnik internally will fix the aspect ratio of the bounding box # to match the aspect ratio of the target image width and height # This behavior is controlled by setting the `m.aspect_fix_mode` # and defaults to GROW_BBOX, but you can also change it to alter # the target image size by setting aspect_fix_mode to GROW_CANVAS #m.aspect_fix_mode = mapnik.GROW_CANVAS # Note: aspect_fix_mode is only available in Mapnik >= 0.6.0 m.zoom_to_box(merc_bbox) # render the map to an image im = mapnik.Image(imgx, imgy) mapnik.render(m, im) im.save(map_uri, 'png') sys.stdout.write('output image to %s!\n' % map_uri) # Note: instead of creating an image, rendering to it, and then # saving, we can also do this in one step like: # mapnik.render_to_file(m, map_uri,'png') # And in Mapnik >= 0.7.0 you can also use `render_to_file()` to output # to Cairo supported formats if you have Mapnik built with Cairo support # For example, to render to pdf or svg do: # mapnik.render_to_file(m, "image.pdf") #mapnik.render_to_file(m, "image.svg")
def _test_grayscale_subquery(lbl, pixtype, value): # # 3 8 13 # +---+---+---+ # 3 | v | v | v | NOTE: writes different color # +---+---+---+ in 13,8 and 8,13 # 8 | v | v | a | # +---+---+---+ # 13 | v | b | v | # +---+---+---+ # val_a = int(value / 3) val_b = val_a * 2 sql = "(select 3 as i, " \ " ST_SetValues(" \ " ST_SetValues(" \ " ST_AsRaster(" \ " ST_MakeEnvelope(0,0,14,14), " \ " 1.0, -1.0, '%s', %s" \ " ), " \ " 11, 6, 4, 5, %s::float8" \ " )," \ " 6, 11, 5, 4, %s::float8" \ " ) as \"R\"" \ ") as foo" % (pixtype, value, val_a, val_b) rescale = 0 clip = 0 if rescale: lbl += ' Sc' if clip: lbl += ' Cl' ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table=sql, raster_field='"R"', use_overviews=1, prescale_rasters=rescale, clip_rasters=clip) fs = ds.featureset() feature = fs.next() eq_(feature['i'], 3) lyr = mapnik.Layer('grayscale_subquery') lyr.datasource = ds expenv = mapnik.Box2d(0, 0, 14, 14) env = lyr.envelope() assert_almost_equal(env.minx, expenv.minx, places=0) assert_almost_equal(env.miny, expenv.miny, places=0) assert_almost_equal(env.maxx, expenv.maxx, places=0) assert_almost_equal(env.maxy, expenv.maxy, places=0) mm = mapnik.Map(15, 15) style = mapnik.Style() sym = mapnik.RasterSymbolizer() rule = mapnik.Rule() rule.symbols.append(sym) style.rules.append(rule) mm.append_style('foo', style) lyr.styles.append('foo') mm.layers.append(lyr) mm.zoom_to_box(expenv) im = mapnik.Image(mm.width, mm.height) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:full') expected = 'images/support/pgraster/%s-%s-%s-%s.png' % ( lyr.name, lbl, pixtype, value) compare_images(expected, im) h = format(value, '02x') hex_v = h + h + h + 'ff' hex_v = hex_v.encode() h = format(val_a, '02x') hex_a = h + h + h + 'ff' hex_a = hex_a.encode() h = format(val_b, '02x') hex_b = h + h + h + 'ff' hex_b = hex_b.encode() eq_(hexlify(im.view(3, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(13, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(3, 8, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 8, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(13, 8, 1, 1).tostring()), hex_a) eq_(hexlify(im.view(3, 13, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 13, 1, 1).tostring()), hex_b) eq_(hexlify(im.view(13, 13, 1, 1).tostring()), hex_v)
def legend_image(legend, zoom, gap, position='side', max_edge=None, highres=True): items = legend.legend_items(zoom).select_related() if not items.count(): # no legend items for this zoom, return empty Image return Image.new('RGBA', (0, 0), 'white') if highres: gap *= 2 params = items.aggregate(Max('width_highres'), Max('legend_item_name__width_highres')) max_image_width = params['width_highres__max'] + 2*gap max_name_width = params['legend_item_name__width_highres__max'] else: params = items.aggregate(Max('width'), Max('legend_item_name__width')) max_image_width = params['width__max'] + 2*gap max_name_width = params['legend_item_name__width__max'] column_width = max_image_width + max_name_width max_height = gap*(len(items) + 1) if highres: for item in items: max_height += max(item.legend_item_name.height_highres, item.height_highres) else: for item in items: max_height += max(item.legend_item_name.height, item.height) height = max_height num_columns = 1 if position == 'side' and max_height > max_edge: num_columns = max_height / max_edge + 1 height = max_edge elif position == 'bottom' and max_edge > column_width: num_columns = max_edge / column_width height = int(1.05 * max_height / num_columns) width = column_width * num_columns + gap image = mapnik.Image(width, height) image.background = mapnik.Color('white') y = gap column = 0 for item in items: if highres: image_height = item.height_highres name_height = item.legend_item_name.height_highres image_width = item.width_highres path = item.image_highres.path.encode('utf-8') name_path = item.legend_item_name.image_highres.path.encode('utf-8') else: image_height = item.height name_height = item.legend_item_name.height image_width = item.width path = item.image.path.encode('utf-8') name_path = item.legend_item_name.image.path.encode('utf-8') shift = max(name_height, image_height) name_y = y image_y = y if image_height > name_height: name_y = y + (image_height - name_height) / 2 else: image_y = y + (name_height - image_height) / 2 image.blend(column * column_width + max_image_width / 2 - image_width / 2, image_y, mapnik.Image.open(path), 1) image.blend(column * column_width + max_image_width, name_y, mapnik.Image.open(name_path), 1) y = y + shift + gap if y + shift > height: y = gap column += 1 return Image.open(StringIO(image.tostring('png')))
def map_image(zoom, left, bottom, right, top, line, orientation='n', highres=True): mapfile = settings.MAPNIK_STYLES + "mapnik2normal.xml" if orientation != 'n': mapfile = settings.MAPNIK_STYLES + "mapnik2orlice_%s.xml" % str(orientation) imgx, imgy = get_image_size(zoom, top, left, bottom, right) if orientation in ('w', 'e'): imgx, imgy = imgy, imgx if highres: mapfile = settings.MAPNIK_STYLES + "mapnik2print.xml" if orientation != 'n': mapfile = settings.MAPNIK_STYLES + "mapnik2print_orlice_%s.xml" % str(orientation) imgx = 2*imgx imgy = 2*imgy m = mapnik.Map(imgx, imgy) mapnik.load_map(m, mapfile) prj = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0' ' +k=1.0 +units=m +nadgrids=@null +no_defs +over') # North on top n0 = prj.forward(mapnik.Coord(left, bottom)) n1 = prj.forward(mapnik.Coord(right, top)) # East on top e0 = mapnik.Coord(-n0.y, n0.x) e1 = mapnik.Coord(-n1.y, n1.x) # South on top s0 = mapnik.Coord(-n1.x, -n1.y) s1 = mapnik.Coord(-n0.x, -n0.y) # West on top w0 = mapnik.Coord(-e1.x, -e1.y) w1 = mapnik.Coord(-e0.x, -e0.y) # bottom_left = prj.forward(mapnik.Coord(left, bottom)) # top_right = prj.forward(mapnik.Coord(right, top)) boxes = {'n': mapnik.Box2d(n0.x, n0.y, n1.x, n1.y), 'e': mapnik.Box2d(e0.x, e0.y, e1.x, e1.y), 's': mapnik.Box2d(s0.x, s0.y, s1.x, s1.y), 'w': mapnik.Box2d(w0.x, w0.y, w1.x, w1.y) } if line: gpxstyle = mapnik.Style() gpxrule = mapnik.Rule() lns = mapnik.LineSymbolizer() stroke = mapnik.Stroke() stroke.color = mapnik.Color('#FF6600') if highres: stroke.width = 10 else: stroke.width = 5 stroke.opacity = 0.9 stroke.line_join = mapnik.line_join.names['round'] stroke.line_cap = mapnik.line_cap.names['round'] lns.stroke = stroke gpxrule.symbols.append(lns) gpxstyle.rules.append(gpxrule) m.append_style('gpxstyle', gpxstyle) gpxlayer = mapnik.Layer('gpx') gpxlayer.datasource = mapnik.Ogr(file=line, layer='OGRGeoJSON') gpxlayer.styles.append('gpxstyle') m.layers.append(gpxlayer) bbox = boxes[orientation] m.zoom_to_box(bbox) im = mapnik.Image(imgx, imgy) mapnik.render(m, im) return Image.open(StringIO(im.tostring('png')))
def getTile(self, x, y, z, **kwargs): if self.projection: mapSrs = self.projection layerSrs = self.getProj4String() extent = None overscan = 0 if not hasattr(self, '_repeatLongitude'): # If the original dataset is in a latitude/longitude # projection, and does cover more than 360 degrees in longitude # (with some slop), and is outside of the bounds of # [-180, 180], we want to render it twice, once at the # specified longitude and once offset to ensure that we cover # [-180, 180]. This is done by altering the projection's # prime meridian by 360 degrees. If none of the dataset is in # the range of [-180, 180], this does't apply the shift either. self._repeatLongitude = None if self._proj4Proj(layerSrs).crs.is_geographic: bounds = self.getBounds() if bounds['xmax'] - bounds['xmin'] < 361: if bounds['xmin'] < -180 and bounds['xmax'] > -180: self._repeatLongitude = layerSrs + ' +pm=+360' elif bounds['xmax'] > 180 and bounds['xmin'] < 180: self._repeatLongitude = layerSrs + ' +pm=-360' else: mapSrs = '+proj=longlat +axis=enu' layerSrs = '+proj=longlat +axis=enu' # There appears to be a bug in some versions of mapnik/gdal when # requesting a tile with a bounding box that has a corner exactly # at (0, extentMaxY), so make a slightly larger image and crop it. extent = '0 0 %d %d' % (self.sourceSizeX, self.sourceSizeY) overscan = 1 xmin, ymin, xmax, ymax = self.getTileCorners(z, x, y) if self.projection: # If we are using a projection, the tile could contain no data. # Don't bother having mapnik render the blank tile -- just output # it. bounds = self.getBounds(self.projection) if (xmin >= bounds['xmax'] or xmax <= bounds['xmin'] or ymin >= bounds['ymax'] or ymax <= bounds['ymin']): pilimg = PIL.Image.new('RGBA', (self.tileWidth, self.tileHeight)) return self._outputTile(pilimg, TILE_FORMAT_PIL, x, y, z, applyStyle=False, **kwargs) if overscan: pw = (xmax - xmin) / self.tileWidth py = (ymax - ymin) / self.tileHeight xmin, xmax = xmin - pw * overscan, xmax + pw * overscan ymin, ymax = ymin - py * overscan, ymax + py * overscan with self._getTileLock: if not hasattr(self, '_mapnikMap'): mapnik.logger.set_severity(mapnik.severity_type.Debug) m = mapnik.Map(self.tileWidth + overscan * 2, self.tileHeight + overscan * 2, mapSrs) self.addStyle(m, layerSrs, extent) if getattr(self, '_repeatLongitude', None): self.addStyle(m, self._repeatLongitude, extent) self._mapnikMap = m else: m = self._mapnikMap m.zoom_to_box(mapnik.Box2d(xmin, ymin, xmax, ymax)) img = mapnik.Image(self.tileWidth + overscan * 2, self.tileHeight + overscan * 2) mapnik.render(m, img) pilimg = PIL.Image.frombytes('RGBA', (img.width(), img.height()), img.tostring()) if overscan: pilimg = pilimg.crop( (1, 1, pilimg.width - overscan, pilimg.height - overscan)) return self._outputTile(pilimg, TILE_FORMAT_PIL, x, y, z, applyStyle=False, **kwargs)
def _test_rgb_8bui_rendering(lbl, tnam, overview, rescale, clip): if rescale: lbl += ' Sc' if clip: lbl += ' Cl' ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table=tnam, use_overviews=1 if overview else 0, prescale_rasters=rescale, clip_rasters=clip) fs = ds.featureset() feature = fs.next() eq_(feature['rid'], 1) lyr = mapnik.Layer('rgba_8bui') lyr.datasource = ds expenv = mapnik.Box2d(-12329035.7652168,4508650.39854396, \ -12328653.0279471,4508957.34625536) env = lyr.envelope() # As the input size is a prime number both horizontally # and vertically, we expect the extent of the overview # tables to be a pixel wider than the original, whereas # the pixel size in geographical units depends on the # overview factor. So we start with the original pixel size # as base scale and multiply by the overview factor. # NOTE: the overview table extent only grows north and east pixsize = 2 # see gdalinfo nodata-edge.tif tol = pixsize * max(overview.split(',')) if overview else 0 assert_almost_equal(env.minx, expenv.minx, places=0) assert_almost_equal(env.miny, expenv.miny, delta=tol) assert_almost_equal(env.maxx, expenv.maxx, delta=tol) assert_almost_equal(env.maxy, expenv.maxy, places=0) mm = mapnik.Map(256, 256) style = mapnik.Style() sym = mapnik.RasterSymbolizer() rule = mapnik.Rule() rule.symbols.append(sym) style.rules.append(rule) mm.append_style('foo', style) lyr.styles.append('foo') mm.layers.append(lyr) mm.zoom_to_box(expenv) im = mapnik.Image(mm.width, mm.height) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:full') #im.save('/tmp/xfull.png') # for debugging # no data eq_(hexlify(im.view(3, 16, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(128, 16, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(250, 16, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(3, 240, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(128, 240, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(250, 240, 1, 1).tostring()), '00000000') # dark brown eq_(hexlify(im.view(174, 39, 1, 1).tostring()), 'c3a698ff') # dark gray eq_(hexlify(im.view(195, 132, 1, 1).tostring()), '575f62ff') # Now zoom over a portion of the env (1/10) newenv = mapnik.Box2d(-12329035.7652168, 4508926.651484220, \ -12328997.49148983,4508957.34625536) mm.zoom_to_box(newenv) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10') #im.save('/tmp/xtenth.png') # for debugging # no data eq_(hexlify(im.view(3, 16, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(128, 16, 1, 1).tostring()), '00000000') eq_(hexlify(im.view(250, 16, 1, 1).tostring()), '00000000') # black eq_(hexlify(im.view(3, 42, 1, 1).tostring()), '000000ff') eq_(hexlify(im.view(3, 134, 1, 1).tostring()), '000000ff') eq_(hexlify(im.view(3, 244, 1, 1).tostring()), '000000ff') # gray eq_(hexlify(im.view(135, 157, 1, 1).tostring()), '4e555bff') # brown eq_(hexlify(im.view(195, 223, 1, 1).tostring()), 'f2cdbaff')
def tile(request, version, shapefile_id, zoom, x, y): shapefile = None try: if version != "1.0": raise Http404 try: shapefile = Shapefile.objects.get(id=shapefile_id) except Shapefile.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) # min(x) = 0, max (x) = if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 # for TILE_WIDTH/HEIGHT==256 # at zoom = 0 extents will be 180 units/degrees xExtent = _unitsPerPixel(zoom) * TILE_WIDTH yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT minLong = xExtent * x - 180.0 minLat = yExtent * y - 90.0 maxLong = minLong + xExtent maxLat = minLat + xExtent if (minLong < -180 or maxLong > 180 or minLat < -90 or maxLat > 90): print "bound error raised" raise Http404 dbFile = "/home/john360/computing/geospatial_dev/geodjango_shapefile_app/DB/geodjango.db" extentStr = "%s,%s,%s,%s" % (minLong, minLat, maxLong, maxLat) map = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, '+proj=longlat +datum=WGS84 +no_defs') map.background = mapnik.Color("#7391ad") # time.sleep (0.3) # Set up the base layer datasource = \ mapnik.SQLite(file=dbFile, table="shapeEditor_baseMap", key_field="id", # srid=4326, geometry_field="geometry", extent=extentStr, wkb_format="spatialite") baseLayer = mapnik.Layer("baseLayer") baseLayer.datasource = datasource baseLayer.styles.append("baseLayerStyle") rule = mapnik.Rule() rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#b5d19c"))) rule.symbols.append(mapnik.LineSymbolizer(mapnik.Color("#404040"), 0.2)) style = mapnik.Style() style.rules.append(rule) map.append_style("baseLayerStyle", style) map.layers.append(baseLayer) # Define the feature layer geometryField = utils.calcGeometryField(shapefile.geom_type) query = '( select ' + geometryField + \ ' from "shapeEditor_feature" where ' + \ 'shapefile_id = ' + str(shapefile.id) + ' ) as geom' dbSettings = settings.DATABASES['default'] datasource = \ mapnik.PostGIS(user=dbSettings['USER'], password=dbSettings['PASSWORD'], dbname=dbSettings['NAME'], table=query, srid=4326, geometry_field=geometryField, geometry_table='"shapeEditor_feature"') featureLayer = mapnik.Layer("featureLayer") featureLayer.datasource = datasource featureLayer.styles.append("featureLayerStyle") rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) elif shapefile.geom_type in ["Polygon", "Multipolygon"]: rule.symbols.append( mapnik.PolygonSymbolizer(mapnik.Color("#b5d19c"))) rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 1)) style = mapnik.Style() style.rules.append(rule) map.append_style("featureLayerStyle", style) map.layers.append(featureLayer) map.zoom_to_box(mapnik.Envelope(minLong, minLat, maxLong, maxLat)) image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT) mapnik.render(map, image) imageData = image.tostring('png') return HttpResponse(imageData, mimetype="image/png") except: traceback.print_exc() return HttpResponse(" ")
def _test_data_subquery(lbl, pixtype, value): # # 3 8 13 # +---+---+---+ # 3 | v | v | v | NOTE: writes different values # +---+---+---+ in 13,8 and 8,13 # 8 | v | v | a | # +---+---+---+ # 13 | v | b | v | # +---+---+---+ # val_a = value / 3 val_b = val_a * 2 sql = "(select 3 as i, " \ " ST_SetValues(" \ " ST_SetValues(" \ " ST_AsRaster(" \ " ST_MakeEnvelope(0,0,14,14), " \ " 1.0, -1.0, '%s', %s" \ " ), " \ " 11, 6, 5, 5, %s::float8" \ " )," \ " 6, 11, 5, 5, %s::float8" \ " ) as \"R\"" \ ") as foo" % (pixtype,value, val_a, val_b) overview = '' rescale = 0 clip = 0 if rescale: lbl += ' Sc' if clip: lbl += ' Cl' ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table=sql, raster_field='R', use_overviews=0 if overview else 0, band=1, prescale_rasters=rescale, clip_rasters=clip) fs = ds.featureset() feature = fs.next() eq_(feature['i'], 3) lyr = mapnik.Layer('data_subquery') lyr.datasource = ds expenv = mapnik.Box2d(0, 0, 14, 14) env = lyr.envelope() assert_almost_equal(env.minx, expenv.minx, places=0) assert_almost_equal(env.miny, expenv.miny, places=0) assert_almost_equal(env.maxx, expenv.maxx, places=0) assert_almost_equal(env.maxy, expenv.maxy, places=0) mm = mapnik.Map(15, 15) style = mapnik.Style() col = mapnik.RasterColorizer() col.default_mode = mapnik.COLORIZER_DISCRETE col.add_stop(val_a, mapnik.Color(0xff, 0x00, 0x00, 255)) col.add_stop(val_b, mapnik.Color(0x00, 0xff, 0x00, 255)) col.add_stop(value, mapnik.Color(0x00, 0x00, 0xff, 255)) sym = mapnik.RasterSymbolizer() sym.colorizer = col rule = mapnik.Rule() rule.symbols.append(sym) style.rules.append(rule) mm.append_style('foo', style) lyr.styles.append('foo') mm.layers.append(lyr) mm.zoom_to_box(expenv) im = mapnik.Image(mm.width, mm.height) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:full') #im.save('/tmp/xfull.png') # for debugging h = format(value, '02x') hex_v = '0000ffff' hex_a = 'ff0000ff' hex_b = '00ff00ff' eq_(hexlify(im.view(3, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(13, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(3, 8, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 8, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(13, 8, 1, 1).tostring()), hex_a) eq_(hexlify(im.view(3, 13, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 13, 1, 1).tostring()), hex_b) eq_(hexlify(im.view(13, 13, 1, 1).tostring()), hex_v)
def test_quality_threshold(): im = mapnik.Image(256, 256) im.tostring('webp:quality=99.99000') im.tostring('webp:quality=0') im.tostring('webp:quality=0.001')
def _test_rgba_subquery(lbl, pixtype, r, g, b, a, g1, b1): # # 3 8 13 # +---+---+---+ # 3 | v | v | h | NOTE: writes different alpha # +---+---+---+ in 13,8 and 8,13 # 8 | v | v | a | # +---+---+---+ # 13 | v | b | v | # +---+---+---+ # sql = "(select 3 as i, " \ " ST_SetValues(" \ " ST_SetValues(" \ " ST_AddBand(" \ " ST_AddBand(" \ " ST_AddBand(" \ " ST_AsRaster(" \ " ST_MakeEnvelope(0,0,14,14), " \ " 1.0, -1.0, '%s', %s" \ " )," \ " '%s', %d::float" \ " ), " \ " '%s', %d::float" \ " ), " \ " '%s', %d::float" \ " ), " \ " 2, 11, 6, 4, 5, %s::float8" \ " )," \ " 3, 6, 11, 5, 4, %s::float8" \ " ) as r" \ ") as foo" % (pixtype, r, pixtype, g, pixtype, b, pixtype, a, g1, b1) overview = '' rescale = 0 clip = 0 if rescale: lbl += ' Sc' if clip: lbl += ' Cl' ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table=sql, raster_field='r', use_overviews=0 if overview else 0, prescale_rasters=rescale, clip_rasters=clip) fs = ds.featureset() feature = fs.next() eq_(feature['i'], 3) lyr = mapnik.Layer('rgba_subquery') lyr.datasource = ds expenv = mapnik.Box2d(0, 0, 14, 14) env = lyr.envelope() assert_almost_equal(env.minx, expenv.minx, places=0) assert_almost_equal(env.miny, expenv.miny, places=0) assert_almost_equal(env.maxx, expenv.maxx, places=0) assert_almost_equal(env.maxy, expenv.maxy, places=0) mm = mapnik.Map(15, 15) style = mapnik.Style() sym = mapnik.RasterSymbolizer() rule = mapnik.Rule() rule.symbols.append(sym) style.rules.append(rule) mm.append_style('foo', style) lyr.styles.append('foo') mm.layers.append(lyr) mm.zoom_to_box(expenv) im = mapnik.Image(mm.width, mm.height) t0 = time.time() # we want wall time to include IO waits mapnik.render(mm, im) lap = time.time() - t0 log('T ' + str(lap) + ' -- ' + lbl + ' E:full') im.save('/tmp/xfull.png') # for debugging hex_v = format(r << 24 | g << 16 | b << 8 | a, '08x') hex_a = format(r << 24 | g1 << 16 | b << 8 | a, '08x') hex_b = format(r << 24 | g << 16 | b1 << 8 | a, '08x') eq_(hexlify(im.view(3, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(13, 3, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(3, 8, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 8, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(13, 8, 1, 1).tostring()), hex_a) eq_(hexlify(im.view(3, 13, 1, 1).tostring()), hex_v) eq_(hexlify(im.view(8, 13, 1, 1).tostring()), hex_b) eq_(hexlify(im.view(13, 13, 1, 1).tostring()), hex_v)
def test_expected_encodings(): fails = [] try: for opt in opts: im = mapnik.Image(256, 256) expected = gen_filepath('blank', opt) actual = os.path.join(tmp_dir, os.path.basename(expected)) if generate or not os.path.exists(expected): print 'generating expected image %s' % expected im.save(expected, opt) im.save(actual, opt) try: expected_bytes = mapnik.Image.open(expected).tostring() except RuntimeError: # this will happen if libweb is old, since it cannot open images created by more recent webp print 'warning, cannot open webp expected image (your libwebp is likely too old)' continue if mapnik.Image.open(actual).tostring() != expected_bytes: fails.append('%s (actual) not == to %s (expected)' % (actual, expected)) for opt in opts: im = mapnik.Image(256, 256) im.background = mapnik.Color('green') expected = gen_filepath('solid', opt) actual = os.path.join(tmp_dir, os.path.basename(expected)) if generate or not os.path.exists(expected): print 'generating expected image %s' % expected im.save(expected, opt) im.save(actual, opt) try: expected_bytes = mapnik.Image.open(expected).tostring() except RuntimeError: # this will happen if libweb is old, since it cannot open images created by more recent webp print 'warning, cannot open webp expected image (your libwebp is likely too old)' continue if mapnik.Image.open(actual).tostring() != expected_bytes: fails.append('%s (actual) not == to %s (expected)' % (actual, expected)) for opt in opts: im = mapnik.Image.open( 'images/support/transparency/aerial_rgba.png') expected = gen_filepath('aerial_rgba', opt) actual = os.path.join(tmp_dir, os.path.basename(expected)) if generate or not os.path.exists(expected): print 'generating expected image %s' % expected im.save(expected, opt) im.save(actual, opt) try: expected_bytes = mapnik.Image.open(expected).tostring() except RuntimeError: # this will happen if libweb is old, since it cannot open images created by more recent webp print 'warning, cannot open webp expected image (your libwebp is likely too old)' continue if mapnik.Image.open(actual).tostring() != expected_bytes: fails.append('%s (actual) not == to %s (expected)' % (actual, expected)) # disabled to avoid failures on ubuntu when using old webp packages #eq_(fails,[],'\n'+'\n'.join(fails)) except RuntimeError, e: print e
gamma = lambda x,g: 255.0 * (float(x) / 255.0) ** (1.0/float(g)) tileim = Image.eval(tileim,lambda x: highCompress(lowCompress(gamma(x,1.3)))) sys.stdout.write("done. (%gs/%gs)\n" % (time.clock() - t0,time.time() - t0_)) sys.stdout.flush() else: t0 = time.clock() t0_ = time.time() sys.stdout.write("\tRendering '%s'..." % (mapfile)) sys.stdout.flush() m = mapnik.Map(mtileSize,mtileSize) mapnik.load_map(m, "%s/~map-%s.xml" % (mappath,mapfile), True) m.buffer_size = 512 if mapfile == "text" else 48 m.resize(mtileSize, mtileSize) m.zoom_to_box(bbox) tileim = mapnik.Image(mtileSize, mtileSize) mapnik.render(m, tileim) tileim = Image.fromstring('RGBA',(mtileSize, mtileSize),tileim.tostring()) sys.stdout.write("done. (%gs/%gs)\n" % (time.clock() - t0,time.time() - t0_)) sys.stdout.flush() im = composite(mtileSize,tileim,im,opts) k += 1 t0 = time.clock() t0_ = time.time() sys.stdout.write("\tCroping tiles...") sys.stdout.flush() im.convert('RGB') for i in range(mtileSize/TILE_SIZE):
#popplaces_rule.symbols.append(popplaces_text_symbolizer) popplaces_style.rules.append(popplaces_rule) m.append_style('popplaces', popplaces_style) popplaces_lyr.styles.append('popplaces') m.layers.append(popplaces_lyr) # Draw map # Set the initial extent of the map in 'master' spherical Mercator projection m.zoom_to_box( mapnik.Box2d(-8024477.28459, 5445190.38849, -7381388.20071, 5662941.44855)) # Render map im = mapnik.Image(m.width, m.height) mapnik.render(m, im) # Save image to files images_ = [] if mapnik.has_png(): im.save('demo.png', 'png') # true-colour RGBA images_.append('demo.png') # old behavior, now can do 'png8:c=256' im.save('demo256.png', 'png256') # save to palette based (max 256 colours) png images_.append('demo256.png') im.save('demo64_binary_transparency.png', 'png8:c=64:t=1') images_.append('demo64_binary_transparency.png')
def test_grayscale_conversion(): im = mapnik.Image(2, 2) im.fill(mapnik.Color('white')) im.set_grayscale_to_alpha() pixel = im.get_pixel(0, 0) eq_((pixel >> 24) & 0xff, 255)
def renderTile(self, tile): import mapnik if self.mapnik: m = self.mapnik else: if self.fonts: engine = mapnik.FontEngine.instance() for font in self.fonts: engine.register_font(font) # Init it as 0,0 m = mapnik.Map(0, 0) mapnik.load_map(m, self.mapfile) if self.projection: m.srs = self.projection # Restrict layer list, if requested if self.layers and self.layers != self.name: layers = self.layers.split(",") for layer_num in range(len(m.layers) - 1, -1, -1): l = m.layers[layer_num] if l.name not in layers: del m.layers[layer_num] if self.debug: print >> sys.stderr, "Removed layer %s loaded from %s, not in list: %s" % ( l.name, self.mapfile, layers) # this will insure that it gets cached in mod_python self.mapnik = m # Set the mapnik size to match the size of the current tile m.width = tile.size()[0] m.height = tile.size()[1] bbox = tile.bounds() bbox = mapnik.Envelope(bbox[0], bbox[1], bbox[2], bbox[3]) m.zoom_to_box(bbox) im = mapnik.Image(*tile.size()) mapnik.render(m, im) if hasattr(im, 'tostring'): if self.paletted: data = im.tostring('png256') else: data = im.tostring(self.extension) tile.data = data return tile.data elif hasattr(mapnik, 'rawdata'): data = mapnik.rawdata(im) import PIL.Image, StringIO im = PIL.Image.fromstring('RGBA', tile.size(), data) buffer = StringIO.StringIO() if self.paletted: print >> sys.stderr, "Mapnik's 8-bit (png256) format not supported with PIL" im.save(buffer, self.extension) buffer.seek(0) tile.data = buffer.read() return tile.data else: raise Exception( "Something is wrong: your version of Mapnik can't create a string from an image." )
# Create map map = mapnik.Map(width, height) # Load map configuration mapnik.load_map(map, "/openstreetmap-carto/mapnik.xml") # Zoom the map to the bounding box map.zoom_to_box(bbox) # Fork so that we can handle crashes rendering the map pid = os.fork() # Render the map if pid == 0: if form.getvalue("format") == "png": image = mapnik.Image(map.width, map.height) mapnik.render(map, image) png = image.tostring("png") output_headers("image/png", "map.png", len(png)) sys.stdout.write(png) elif form.getvalue("format") == "jpeg": image = mapnik.Image(map.width, map.height) mapnik.render(map, image) jpeg = image.tostring("jpeg") output_headers("image/jpeg", "map.jpg", len(jpeg)) sys.stdout.write(jpeg) elif form.getvalue("format") == "svg": file = tempfile.NamedTemporaryFile(prefix = "export") surface = cairo.SVGSurface(file.name, map.width, map.height) mapnik.render(map, surface) surface.finish()
if options.output == '-': outfile = tempfile.TemporaryFile(mode='w+b') if need_cairo: if HAS_CAIRO: surface = cairo.SVGSurface( outfile, size[0], size[1]) if fmt == 'svg' else cairo.PDFSurface( outfile, size[0], size[1]) mapnik.render(m, surface, scale_factor, 0, 0) surface.finish() else: mapnik.render_to_file(m, outfile, fmt) else: if options.tiles == 1: im = mapnik.Image(size[0], size[1]) mapnik.render(m, im, scale_factor) im.save(outfile, fmt) else: # we cannot make mapnik calculate scale for us, so fixing aspect ratio outselves rdiff = (bbox.maxx - bbox.minx) / (bbox.maxy - bbox.miny) - size[0] / size[1] if rdiff > 0: bbox.height((bbox.maxx - bbox.minx) * size[1] / size[0]) elif rdiff < 0: bbox.width((bbox.maxy - bbox.miny) * size[0] / size[1]) scale = (bbox.maxx - bbox.minx) / size[0] width = max(32, int(math.ceil(1.0 * size[0] / options.tiles))) height = max(32, int(math.ceil(1.0 * size[1] / options.tiles))) m.resize(width, height) m.buffer_size = TILE_BUFFER
def renderLegendElement(sourceFile, elementType, tagList, zoom, imageWidth, map_uri): """ # 'Fake' load a map to use mapnik libxml2 support for large xml files mSource = mapnik.Map(1,1) mapnik.load_map(mSource,sourceFile) inputstylesheet=mapnik.save_map_to_string(mSource) """ # serialize map file with external entities included inputstylesheet = etree.tostring(etree.parse(sourceFile)) # the mapfile (stylesheet made only for legend element rendering # is returned as a string, no file is written on disk # then use mapnik.load_map_from_string mapfile = create_legend_stylesheet(inputstylesheet) # create a new element, which return its bbox and an osm file as # a string osmStr, bound = createOsmElement(elementType, tagList, zoom) # create a named temporary file, mapnik needs a real file # we cannot pass a StringIO nor a string, nor a unnammed # temporary file osmFile = tempfile.NamedTemporaryFile(mode='w+t') osmFile.write(osmStr) #write the osm file osmFile.seek(0) #rewind #--------------------------------------------------- # Set up projection # long/lat in degrees, aka ESPG:4326 and "WGS 84" lonlat = mapnik.Projection('+proj=longlat +datum=WGS84') #bbbox =(lon,lat,maxlon,maxlat) ratio = abs((bound[2] - bound[0]) / (bound[3] - bound[1])) width = imageWidth height = int(width / ratio * 1) # add +1 if highway=path looks blurry FIXME m = mapnik.Map(width, height) mapnik.load_map_from_string(m, mapfile) m.srs = lonlat.params() for l in m.layers: l.datasource = Osm(file=osmFile.name) l.srs = lonlat.params() # uncomment this line to save the mapfile on disk, remember to # NEVER show this file to a stylesheet maintainer: #save_map(m,'mapfile.xml') # render the element and save to disk bbox =lonlat.forward(mapnik.Envelope(mapnik.Coord(bound[0],bound[1]),\ mapnik.Coord(bound[2],bound[3]))) m.zoom_to_box(bbox) im = mapnik.Image(width, height) mapnik.render(m, im) osmFile.close() # closing the datasource view = im.view(0, 0, width, height) # x,y,width,height #print "saving ", map_uri #view.save(map_uri,'png') #'save' the image in a string imgStr = view.tostring('png') # reopen the saved image with PIL to count the color # if 1, the pic is empty #img = Image.open(map_uri) # kind of StringIO() for images instead: imgParser = ImageFile.Parser() imgParser.feed(imgStr) img = imgParser.close() if len(img.getcolors()) == 1: print "empty file not saved", map_uri #delete the pic file if empty #os.remove(map_uri) else: # Crop the file to its smaller extent # Cropping the pic allow a much concise html page formatting, # use CSS for the rest img256 = img.convert('L') imgbg = ImageChops.constant(img256, img256.getpixel((0, 0))) box = ImageChops.difference(img256, imgbg).getbbox() out = img.crop(box) print "saving ", map_uri out.save(map_uri) return True
def test_render_with_scale_factor_zero_throws(): m = mapnik.Map(256, 256) im = mapnik.Image(256, 256) mapnik.render(m, im, 0.0)
def tile(request, version, shapefile_id, zoom, x, y): try: if version != "1.0": raise Http404 try: shapefile = Shapefile.objects.get(id=shapefile_id) except Shapefile.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) * TILE_WIDTH yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT minLong = x * xExtent - 180.0 minLat = y * yExtent - 90.0 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -180 or maxLong > 180 or minLat < -90 or maxLat > 90): print "Map extent out of bounds:",minLong,minLat,maxLong,maxLat raise Http404 ####################################################### map = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, str("+proj=longlat +datum=WGS84")) map.background = mapnik.Color(str("#7391ad")) dbSettings = settings.DATABASES['default'] datasource = mapnik.PostGIS(user=str(dbSettings['USER']),password=str(dbSettings['PASSWORD']), dbname=str(dbSettings['NAME']),table='tms_basemap', srid=4326, geometry_field="geometry", geometry_table='tms_basemap', port=5433) baseLayer = mapnik.Layer(str("baseLayer")) baseLayer.datasource = datasource baseLayer.styles.append(str("baseLayerStyle")) rule = mapnik.Rule() rule.symbols.append( mapnik.PolygonSymbolizer(mapnik.Color(str("#b5d19c")))) rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color(str("#404040")), 0.2)) style = mapnik.Style() style.rules.append(rule) map.append_style(str("baseLayerStyle"), style) #### map.layers.append(baseLayer) geometry_field = \ utils.calc_geometry_field(shapefile.geom_type) query = '(SELECT ' + geometry_field \ + ' FROM "shared_feature" WHERE' \ + ' shapefile_id = ' + str(shapefile.id) + ') as geom' print query print dbSettings['USER'],dbSettings['PASSWORD'],dbSettings['NAME'],query,geometry_field datasource = \ mapnik.PostGIS(user=dbSettings['USER'], password=dbSettings['PASSWORD'], dbname=dbSettings['NAME'], port=dbSettings['PORT'], srid=4326, table=query, geometry_field=geometry_field, geometry_table='shared_feature', ) featureLayer = mapnik.Layer(str("featureLayer")) featureLayer.datasource = datasource featureLayer.styles.append(str("featureLayerStyle")) rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: rule.symbols.append(mapnik.PointSymbolizer()) elif shapefile.geom_type in ["LineString", "MultiLineString"]: rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: rule.symbols.append( mapnik.PolygonSymbolizer(mapnik.Color(str("#f7edee")))) rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color(str("#000000")), 0.5)) style = mapnik.Style() style.rules.append(rule) map.append_style(str("featureLayerStyle"), style) map.layers.append(featureLayer) map.zoom_to_box(mapnik.Box2d(minLong, minLat, maxLong, maxLat)) image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT) mapnik.render(map, image) imageData = image.tostring(str('png')) print imageData return HttpResponse(imageData, content_type="image/png") except: traceback.print_exc() return HttpResponse("Error")