Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel.
975168
def export_image(self, bbox, zoomlevel, imagepath):
        
        assert has_pil, _("Cannot export image without python PIL")
        grid = self.grid_tiles(bbox, zoomlevel)
        width = len(grid[0])
        height = len(grid)
        widthpix = width * self.tile_size
        heightpix = height * self.tile_size

        result = Image.new("RGBA", (widthpix, heightpix))
        offset = (0, 0)
        for i, row in enumerate(grid):
            for j, (x, y) in enumerate(row):
                offset = (j * self.tile_size, i * self.tile_size)
                img = self._tile_image(self.tile((zoomlevel, x, y)))
                result.paste(img, offset)
        logger.info(_("Save resulting image to '%s'") % imagepath)
        result.save(imagepath)
864886
def tile(ctx, point, zoom):
    """"""
    tile = TilePyramid(
        ctx.obj['grid'],
        tile_size=ctx.obj['tile_size'],
        metatiling=ctx.obj['metatiling']
    ).tile_from_xy(*point, zoom=zoom)
    if ctx.obj['output_format'] == 'Tile':
        click.echo('%s %s %s' % tile.id)
    elif ctx.obj['output_format'] == 'WKT':
        click.echo(tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']))
    elif ctx.obj['output_format'] == 'GeoJSON':
        click.echo(
            geojson.dumps(
                geojson.FeatureCollection([
                    geojson.Feature(
                        geometry=tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']),
                        properties=dict(
                            zoom=tile.zoom,
                            row=tile.row,
                            col=tile.col
                        )
                    )
                ])
            )
        )
636572
private GeoPackageTile drawTile(TileMatrix tileMatrix,
			TileResultSet tileResults, BoundingBox requestProjectedBoundingBox,
			int tileWidth, int tileHeight) {

		// Draw the resulting bitmap with the matching tiles
		GeoPackageTile geoPackageTile = null;
		Graphics graphics = null;
		while (tileResults.moveToNext()) {

			// Get the next tile
			TileRow tileRow = tileResults.getRow();
			BufferedImage tileDataImage;
			try {
				tileDataImage = tileRow.getTileDataImage();
			} catch (IOException e) {
				throw new GeoPackageException(
						"Failed to read the tile row image data", e);
			}

			// Get the bounding box of the tile
			BoundingBox tileBoundingBox = TileBoundingBoxUtils.getBoundingBox(
					tileSetBoundingBox, tileMatrix, tileRow.getTileColumn(),
					tileRow.getTileRow());

			// Get the bounding box where the requested image and
			// tile overlap
			BoundingBox overlap = requestProjectedBoundingBox
					.overlap(tileBoundingBox);

			// If the tile overlaps with the requested box
			if (overlap != null) {

				// Get the rectangle of the tile image to draw
				ImageRectangle src = TileBoundingBoxJavaUtils.getRectangle(
						tileMatrix.getTileWidth(), tileMatrix.getTileHeight(),
						tileBoundingBox, overlap);

				// Get the rectangle of where to draw the tile in
				// the resulting image
				ImageRectangle dest = TileBoundingBoxJavaUtils.getRectangle(
						tileWidth, tileHeight, requestProjectedBoundingBox,
						overlap);

				if (src.isValid() && dest.isValid()) {

					if (imageFormat != null) {

						// Create the bitmap first time through
						if (geoPackageTile == null) {
							BufferedImage bufferedImage = ImageUtils
									.createBufferedImage(tileWidth, tileHeight,
											imageFormat);
							graphics = bufferedImage.getGraphics();
							geoPackageTile = new GeoPackageTile(tileWidth,
									tileHeight, bufferedImage);
						}

						// Draw the tile to the image
						graphics.drawImage(tileDataImage, dest.getLeft(),
								dest.getTop(), dest.getRight(),
								dest.getBottom(), src.getLeft(), src.getTop(),
								src.getRight(), src.getBottom(), null);
					} else {

						// Verify only one image was found and
						// it lines up perfectly
						if (geoPackageTile != null || !src.equals(dest)) {
							throw new GeoPackageException(
									"Raw image only supported when the images are aligned with the tile format requiring no combining and cropping");
						}

						geoPackageTile = new GeoPackageTile(tileWidth,
								tileHeight, tileRow.getTileData());
					}
				}
			}
		}

		// Check if the entire image is transparent
		if (geoPackageTile != null && geoPackageTile.getImage() != null
				&& ImageUtils.isFullyTransparent(geoPackageTile.getImage())) {
			geoPackageTile = null;
		}

		return geoPackageTile;
	}
192550
function(bounds) {
        var url = "";
        bounds = this.adjustBounds(bounds);
        
        // create an arcxml request to generate the image
        var axlReq = new OpenLayers.Format.ArcXML( 
            OpenLayers.Util.extend(this.options, {
                requesttype: "image",
                envelope: bounds.toArray(),
                tileSize: this.tileSize
            })
        );
        
        // create a synchronous ajax request to get an arcims image
        var req = new OpenLayers.Request.POST({
            url: this.getFullRequestString(),
            data: axlReq.write(),
            async: false
        });
        
        // if the response exists
        if (req != null) {
            var doc = req.responseXML;

            if (!doc || !doc.documentElement) {            
                doc = req.responseText;
            }

            // create a new arcxml format to read the response
            var axlResp = new OpenLayers.Format.ArcXML();
            var arcxml = axlResp.read(doc);
            url = this.getUrlOrImage(arcxml.image.output);
        }
        
        return url;
    }
65191
function (bounds) {
        bounds = this.adjustBounds(bounds);
        var res = this.getServerResolution();
        var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
        var y = Math.round((this.tileOrigin.lat - bounds.top) / (res * this.tileSize.h));
        var z = this.getZoomForResolution( res );

        var tileIndex = x + y * this.tierSizeInTiles[z].w + this.tileCountUpToTier[z];
        var path = "TileGroup" + Math.floor( (tileIndex) / 256 ) +
            "/" + z + "-" + x + "-" + y + ".jpg";
        var url = this.url;
        if (OpenLayers.Util.isArray(url)) {
            url = this.selectUrl(path, url);
        }
        return url + path;
    }
548296
def tileAddress(self, zoom, point):
        ""
        [x, y] = point
        assert x <= self.MAXX and x >= self.MINX
        assert y <= self.MAXY and y >= self.MINY
        assert zoom in range(0, len(self.RESOLUTIONS))

        tileS = self.tileSize(zoom)
        offsetX = abs(x - self.MINX)
        if self.originCorner == 'bottom-left':
            offsetY = abs(y - self.MINY)
        elif self.originCorner == 'top-left':
            offsetY = abs(self.MAXY - y)
        col = offsetX / tileS
        row = offsetY / tileS
        # We are exactly on the edge of a tile and the extent
        if x in (self.MINX, self.MAXX) and col.is_integer():
            col = max(0, col - 1)
        if y in (self.MINY, self.MAXY) and row.is_integer():
            row = max(0, row - 1)
        return [
            int(math.floor(col)),
            int(math.floor(row))
        ]
879943
public BufferedImage drawTile(int[][] unsignedPixelValues) {

		int tileWidth = unsignedPixelValues[0].length;
		int tileHeight = unsignedPixelValues.length;

		BufferedImage image = createImage(tileWidth, tileHeight);
		WritableRaster raster = image.getRaster();
		for (int x = 0; x < tileWidth; x++) {
			for (int y = 0; y < tileHeight; y++) {
				int unsignedPixelValue = unsignedPixelValues[y][x];
				setPixelValue(raster, x, y, unsignedPixelValue);
			}
		}

		return image;
	}
126246
public static void boundImage( GrayF32 img , float min , float max ) {
		ImplPixelMath.boundImage(img,min,max);
	}
676446
private static int readFormatTiles(GeoPackage geoPackage, String tileTable,
			String imageFormat, TileFormatType tileType, boolean rawImage,
			TileDirectory tileDirectory) throws IOException, SQLException {

		int created = 0;

		// Find the bounding box that includes all the zoom levels
		BoundingBox webMercatorBoundingBox = null;

		for (ZoomDirectory zoomDirectory : tileDirectory.zooms.values()) {

			int minY = zoomDirectory.minY;
			int maxY = zoomDirectory.maxY;

			// If TMS format, flip the y values
			if (tileType == TileFormatType.TMS) {
				int tempMaxY = TileBoundingBoxUtils.getYAsOppositeTileFormat(
						zoomDirectory.zoom, minY);
				minY = TileBoundingBoxUtils.getYAsOppositeTileFormat(
						zoomDirectory.zoom, maxY);
				maxY = tempMaxY;
			}

			// Get the bounding box at the zoom level
			TileGrid tileGrid = new TileGrid(zoomDirectory.minX, minY,
					zoomDirectory.maxX, maxY);
			BoundingBox zoomBoundingBox = TileBoundingBoxUtils
					.getWebMercatorBoundingBox(tileGrid, zoomDirectory.zoom);

			// Set or expand the bounding box
			if (webMercatorBoundingBox == null) {
				webMercatorBoundingBox = zoomBoundingBox;
			} else {
				webMercatorBoundingBox = webMercatorBoundingBox
						.union(zoomBoundingBox);
			}
		}

		// Get the bounding box that includes all zoom levels at the min zoom
		// level
		TileGrid totalTileGrid = TileBoundingBoxUtils.getTileGrid(
				webMercatorBoundingBox, tileDirectory.minZoom);
		BoundingBox totalWebMercatorBoundingBox = TileBoundingBoxUtils
				.getWebMercatorBoundingBox(totalTileGrid, tileDirectory.minZoom);

		// Create the user tile table
		List<TileColumn> columns = TileTable.createRequiredColumns();
		TileTable table = new TileTable(tileTable, columns);
		geoPackage.createTileTable(table);

		// Get SRS values
		SpatialReferenceSystemDao srsDao = geoPackage
				.getSpatialReferenceSystemDao();
		SpatialReferenceSystem srsWebMercator = srsDao
				.getOrCreateFromEpsg(ProjectionConstants.EPSG_WEB_MERCATOR);

		// Create the Tile Matrix Set and Tile Matrix tables
		geoPackage.createTileMatrixSetTable();
		geoPackage.createTileMatrixTable();

		// Create new Contents
		ContentsDao contentsDao = geoPackage.getContentsDao();

		Contents contents = new Contents();
		contents.setTableName(tileTable);
		contents.setDataType(ContentsDataType.TILES);
		contents.setIdentifier(tileTable);
		// contents.setDescription("");
		// contents.setLastChange(new Date());
		contents.setMinX(totalWebMercatorBoundingBox.getMinLongitude());
		contents.setMinY(totalWebMercatorBoundingBox.getMinLatitude());
		contents.setMaxX(totalWebMercatorBoundingBox.getMaxLongitude());
		contents.setMaxY(totalWebMercatorBoundingBox.getMaxLatitude());
		contents.setSrs(srsWebMercator);

		// Create the contents
		contentsDao.create(contents);
		table.setContents(contents);

		// Create new Tile Matrix Set
		TileMatrixSetDao tileMatrixSetDao = geoPackage.getTileMatrixSetDao();

		TileMatrixSet tileMatrixSet = new TileMatrixSet();
		tileMatrixSet.setContents(contents);
		tileMatrixSet.setSrs(srsWebMercator);
		tileMatrixSet.setMinX(totalWebMercatorBoundingBox.getMinLongitude());
		tileMatrixSet.setMinY(totalWebMercatorBoundingBox.getMinLatitude());
		tileMatrixSet.setMaxX(totalWebMercatorBoundingBox.getMaxLongitude());
		tileMatrixSet.setMaxY(totalWebMercatorBoundingBox.getMaxLatitude());
		tileMatrixSetDao.create(tileMatrixSet);

		// Create new Tile Matrix and tile table rows by going through each zoom
		// level
		TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
		TileDao tileDao = geoPackage.getTileDao(tileMatrixSet);
		for (ZoomDirectory zoomDirectory : tileDirectory.zooms.values()) {

			int zoomCount = 0;

			Integer tileWidth = null;
			Integer tileHeight = null;

			// Determine the matrix width and height
			TileGrid zoomTotalTileGrid = TileBoundingBoxUtils.getTileGrid(
					totalWebMercatorBoundingBox, zoomDirectory.zoom);
			long matrixWidth = zoomTotalTileGrid.getMaxX()
					- zoomTotalTileGrid.getMinX() + 1;
			long matrixHeight = zoomTotalTileGrid.getMaxY()
					- zoomTotalTileGrid.getMinY() + 1;

			LOGGER.log(Level.INFO, "Zoom Level: " + zoomDirectory.zoom
					+ ", Width: " + matrixWidth + ", Height: " + matrixHeight
					+ ", Max Tiles: " + (matrixWidth * matrixHeight));

			// Shortcut for raw images with zoom directories with smaller bounds
			// than the bounds of the minimum zoom value
			int minColumn, maxColumn, minRow, maxRow;
			if (rawImage) {
				minColumn = zoomDirectory.minX;
				maxColumn = zoomDirectory.maxX;
				minRow = zoomDirectory.minY;
				maxRow = zoomDirectory.maxY;
			} else {
				minColumn = 0;
				maxColumn = (int) matrixWidth - 1;
				minRow = 0;
				maxRow = (int) matrixHeight - 1;
			}

			// Create the image for each column and row combination
			for (int column = minColumn; column <= maxColumn; column++) {

				for (int row = minRow; row <= maxRow; row++) {

					// Image to draw for the column and row
					BufferedImage image = null;
					Graphics graphics = null;
					byte[] rawImageBytes = null;

					// Determine the bounding box of this column and row
					BoundingBox tileMatrixBoundingBox = TileBoundingBoxUtils
							.getBoundingBox(totalWebMercatorBoundingBox,
									matrixWidth, matrixHeight, column, row);

					// Get the x and y tile grid of the bounding box at the zoom
					// level
					TileGrid tileMatrixGrid = TileBoundingBoxUtils.getTileGrid(
							tileMatrixBoundingBox, zoomDirectory.zoom);

					// Build the column and row image from images in the
					// matching x and y locations
					for (int x = (int) tileMatrixGrid.getMinX(); x <= tileMatrixGrid
							.getMaxX(); x++) {

						// Check if the x directory exists and contains images
						XDirectory xDirectory = zoomDirectory.xValues.get(x);
						if (xDirectory != null) {

							for (int y = (int) tileMatrixGrid.getMinY(); y <= tileMatrixGrid
									.getMaxY(); y++) {

								// If TMS file format, change the y value to TMS
								int yLocation = (int) y;
								if (tileType == TileFormatType.TMS) {
									yLocation = TileBoundingBoxUtils
											.getYAsOppositeTileFormat(
													zoomDirectory.zoom,
													yLocation);
								}

								// Check if the y directory exists and contains
								// images
								YFile yFile = xDirectory.yValues.get(yLocation);
								if (yFile != null) {

									// Get the bounding box of the x, y, z image
									BoundingBox imageBoundingBox = TileBoundingBoxUtils
											.getWebMercatorBoundingBox(x, y,
													zoomDirectory.zoom);

									// Get the bounding box overlap between the
									// column/row image and the x,y,z image
									BoundingBox overlap = tileMatrixBoundingBox
											.overlap(imageBoundingBox);

									// If the tile overlaps
									if (overlap != null) {

										BufferedImage zxyImage = null;

										// Set the tile width and height
										if (tileWidth == null
												|| tileHeight == null) {
											zxyImage = ImageIO.read(yFile.file);
											tileWidth = zxyImage.getWidth();
											tileHeight = zxyImage.getHeight();
										}

										// Get the rectangle of the source image
										ImageRectangle src = TileBoundingBoxJavaUtils
												.getRectangle(tileWidth,
														tileHeight,
														imageBoundingBox,
														overlap);

										// Get the rectangle of where to draw
										// the tile in the resulting image
										ImageRectangle dest = TileBoundingBoxJavaUtils
												.getRectangle(tileWidth,
														tileHeight,
														tileMatrixBoundingBox,
														overlap);

										// Round the rectangles and make sure
										// the bounds are valid
										if (src.isValid() && dest.isValid()) {

											// Save off raw bytes
											if (rawImage) {

												// Verify only one image was
												// found and it lines up
												// perfectly
												if (rawImageBytes != null
														|| !src.equals(dest)) {
													throw new GeoPackageException(
															"Raw image only supported when the images are aligned with the tile format requiring no combining and cropping");
												}

												// Read the file bytes
												rawImageBytes = GeoPackageIOUtils
														.fileBytes(yFile.file);
											} else {

												// Create the image first time
												// through
												if (image == null) {
													image = ImageUtils
															.createBufferedImage(
																	tileWidth,
																	tileHeight,
																	imageFormat);
													graphics = image
															.getGraphics();
												}

												if (zxyImage == null) {
													zxyImage = ImageIO
															.read(yFile.file);
												}

												// Draw the tile to the image
												graphics.drawImage(zxyImage,
														dest.getLeft(),
														dest.getTop(),
														dest.getRight(),
														dest.getBottom(),
														src.getLeft(),
														src.getTop(),
														src.getRight(),
														src.getBottom(), null);
											}

										}
									}
								}
							}
						}
					}

					// If an image was drawn and is not fully transparent,
					// create the tile row
					if ((image != null && !ImageUtils.isFullyTransparent(image))
							|| rawImageBytes != null) {
						TileRow newRow = tileDao.newRow();

						newRow.setZoomLevel(zoomDirectory.zoom);
						newRow.setTileColumn(column);
						newRow.setTileRow(row);
						if (rawImage) {
							newRow.setTileData(rawImageBytes);
						} else {
							newRow.setTileData(image, imageFormat);
						}

						tileDao.create(newRow);

						zoomCount++;

						if (zoomCount % ZOOM_PROGRESS_FREQUENCY == 0) {
							LOGGER.log(Level.INFO, "Zoom " + zoomDirectory.zoom
									+ " Tile Progress... " + zoomCount);
						}
					}
				}

			}

			LOGGER.log(Level.INFO, "Zoom " + zoomDirectory.zoom + " Tiles: "
					+ zoomCount);

			// If tiles were saved for the zoom level, create the tile matrix
			// row
			if (zoomCount > 0) {
				double pixelXSize = TileBoundingBoxUtils.getPixelXSize(
						totalWebMercatorBoundingBox, matrixWidth, tileWidth);
				double pixelYSize = TileBoundingBoxUtils.getPixelYSize(
						totalWebMercatorBoundingBox, matrixHeight, tileHeight);

				TileMatrix tileMatrix = new TileMatrix();
				tileMatrix.setContents(contents);
				tileMatrix.setZoomLevel(zoomDirectory.zoom);
				tileMatrix.setMatrixWidth(matrixWidth);
				tileMatrix.setMatrixHeight(matrixHeight);
				tileMatrix.setTileWidth(tileWidth);
				tileMatrix.setTileHeight(tileHeight);
				tileMatrix.setPixelXSize(pixelXSize);
				tileMatrix.setPixelYSize(pixelYSize);
				tileMatrixDao.create(tileMatrix);

				created += zoomCount;
			}

		}

		return created;
	}
194535
public static TileGrid getTileGridWGS84(BoundingBox boundingBox, int zoom) {

		int tilesPerLat = tilesPerWGS84LatSide(zoom);
		int tilesPerLon = tilesPerWGS84LonSide(zoom);

		double tileSizeLat = tileSizeLatPerWGS84Side(tilesPerLat);
		double tileSizeLon = tileSizeLonPerWGS84Side(tilesPerLon);

		int minX = (int) ((boundingBox.getMinLongitude() + ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH) / tileSizeLon);
		double tempMaxX = (boundingBox.getMaxLongitude() + ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH)
				/ tileSizeLon;
		int maxX = (int) tempMaxX;
		if (tempMaxX % 1 == 0) {
			maxX--;
		}
		maxX = Math.min(maxX, tilesPerLon - 1);

		int minY = (int) (((boundingBox.getMaxLatitude() - ProjectionConstants.WGS84_HALF_WORLD_LAT_HEIGHT) * -1) / tileSizeLat);
		double tempMaxY = ((boundingBox.getMinLatitude() - ProjectionConstants.WGS84_HALF_WORLD_LAT_HEIGHT) * -1)
				/ tileSizeLat;
		int maxY = (int) tempMaxY;
		if (tempMaxY % 1 == 0) {
			maxY--;
		}
		maxY = Math.min(maxY, tilesPerLat - 1);

		TileGrid grid = new TileGrid(minX, minY, maxX, maxY);

		return grid;
	}
1295584
def _draw_tiles(self, x_offset, y_offset, bg):
        """"""
        count = 0
        for layer_name, c_filters, t_filters in self._get_features():
            colour = (self._256_PALETTE[layer_name]
                      if self._screen.colours >= 256 else self._16_PALETTE[layer_name])
            for x, y, z, tile, satellite in sorted(self._tiles.values(), key=lambda k: k[0]):
                # Don't draw the wrong type or zoom of tile.
                if satellite != self._satellite or z != self._zoom:
                    continue

                # Convert tile location into pixels and draw the tile.
                x *= self._size
                y *= self._size
                if satellite:
                    count += self._draw_satellite_tile(
                        tile,
                        int((x-x_offset + self._screen.width // 4) * 2),
                        int(y-y_offset + self._screen.height // 2))
                else:
                    count += self._draw_tile_layer(tile, layer_name, c_filters, colour, t_filters,
                                                   x - x_offset, y - y_offset, bg)
        return count
929365
def coord_to_tilepath(self, lat, lon, zoom):
		'''
		'''
		tile = self.coord_to_tile(lat, lon, zoom)
		return self.tile_to_path(tile)
515293
function(bounds, zoomChanged, dragging) {
        OpenLayers.Layer.prototype.moveTo.apply(this, arguments);

        var firstRendering = (this.tile == null);

        if(zoomChanged || firstRendering) {

            //determine new tile size
            this.setTileSize();

            //determine new position (upper left corner of new bounds)
            var ulPx = this.map.getLayerPxFromLonLat({
                lon: this.extent.left,
                lat: this.extent.top
            });

            if(firstRendering) {
                //create the new tile
                this.tile = new OpenLayers.Tile.Image(this, ulPx, this.extent, 
                                                      null, this.tileSize);
                this.addTileMonitoringHooks(this.tile);
            } else {
                //just resize the tile and set it's new position
                this.tile.size = this.tileSize.clone();
                this.tile.position = ulPx.clone();
            }
            this.tile.draw();
        }
    }
1172071
public Mirage getTileImage (String path, Rectangle bounds, Colorization[] zations)
    {
        return _imgr.getMirage(getImageKey(path), bounds, zations);
    }
494679
@Override
    public Tile getTile(int x, int y, int zoom)
    {
        return getTile(x, y, zoom, true);
    }
417471
def pixels_to_tiles(self, coords, clamp=True):
        
        tile_coords = Vector2()
        tile_coords.X = int(coords[0]) / self.spritesheet[0].width
        tile_coords.Y = int(coords[1]) / self.spritesheet[0].height

        if clamp:
            tile_coords.X, tile_coords.Y = self.clamp_within_range(tile_coords.X, tile_coords.Y)

        return tile_coords
1097381
def _tiles_from_cleaned_bounds(tp, bounds, zoom):
    """"""
    lb = _tile_from_xy(tp, bounds.left, bounds.bottom, zoom, on_edge_use="rt")
    rt = _tile_from_xy(tp, bounds.right, bounds.top, zoom, on_edge_use="lb")
    for tile_id in product([zoom], range(rt.row, lb.row + 1), range(lb.col, rt.col + 1)):
        yield tp.tile(*tile_id)