Write formatted tiles

@param tileDao
@param directory
@param imageFormat
@param width
@param height
@param tileType
@param rawImage
@return
@throws IOException
767429
private static int writeFormatTiles(TileDao tileDao, File directory,
			String imageFormat, Integer width, Integer height,
			TileFormatType tileType, boolean rawImage) throws IOException {

		int tileCount = 0;

		// Get the projection of the tile matrix set
		SpatialReferenceSystem srs = tileDao.getTileMatrixSet().getSrs();
		Projection projection = srs.getProjection();

		// Get the transformation to web mercator
		Projection webMercator = ProjectionFactory
				.getProjection(ProjectionConstants.EPSG_WEB_MERCATOR);
		ProjectionTransform projectionToWebMercator = projection
				.getTransformation(webMercator);

		// Get the bounding box of actual tiles
		BoundingBox zoomBoundingBox = tileDao.getBoundingBox();
		if (projection.isUnit(Units.DEGREES)) {
			zoomBoundingBox = TileBoundingBoxUtils
					.boundDegreesBoundingBoxWithWebMercatorLimits(zoomBoundingBox);
		}
		BoundingBox zoomWebMercatorBoundingBox = zoomBoundingBox
				.transform(projectionToWebMercator);

		GeoPackageTileRetriever retriever = null;
		if (rawImage) {
			retriever = new GeoPackageTileRetriever(tileDao);
		} else {
			retriever = new GeoPackageTileRetriever(tileDao, width, height,
					imageFormat);
		}

		double maxLength = tileDao.getMaxLength();
		double minLength = tileDao.getMinLength();

		double upperMax = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMaxLatitude() - maxLength,
						zoomBoundingBox.getMinLongitude() + maxLength,
						zoomBoundingBox.getMaxLatitude()),
				projectionToWebMercator);
		double upperMin = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMaxLatitude() - minLength,
						zoomBoundingBox.getMinLongitude() + minLength,
						zoomBoundingBox.getMaxLatitude()),
				projectionToWebMercator);

		double lowerMax = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMinLatitude(),
						zoomBoundingBox.getMinLongitude() + maxLength,
						zoomBoundingBox.getMinLatitude() + maxLength),
				projectionToWebMercator);
		double lowerMin = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMinLatitude(),
						zoomBoundingBox.getMinLongitude() + minLength,
						zoomBoundingBox.getMinLatitude() + minLength),
				projectionToWebMercator);

		double maxWebMercatorLength = Math.max(upperMax, lowerMax);
		double minWebMercatorLength = Math.min(upperMin, lowerMin);

		double minZoom = TileBoundingBoxUtils
				.zoomLevelOfTileSize(maxWebMercatorLength);
		double maxZoom = TileBoundingBoxUtils
				.zoomLevelOfTileSize(minWebMercatorLength);

		int minZoomCeiling = (int) Math.ceil(minZoom);
		int maxZoomFloor = (int) Math.floor(maxZoom);

		LOGGER.log(Level.INFO, tileType + " Zoom Range: " + minZoomCeiling
				+ " - " + maxZoomFloor);

		for (int zoomLevel = minZoomCeiling; zoomLevel <= maxZoomFloor; zoomLevel++) {

			File zDirectory = new File(directory, String.valueOf(zoomLevel));
			TileGrid tileGrid = TileBoundingBoxUtils.getTileGrid(
					zoomWebMercatorBoundingBox, zoomLevel);

			int zoomCount = 0;

			LOGGER.log(
					Level.INFO,
					"Zoom Level: " + zoomLevel + ", Min X: "
							+ tileGrid.getMinX() + ", Max X: "
							+ tileGrid.getMaxX() + ", Min Y: "
							+ tileGrid.getMinY() + ", Max Y: "
							+ tileGrid.getMaxY() + ", Max Tiles: "
							+ tileGrid.count());

			for (long x = tileGrid.getMinX(); x <= tileGrid.getMaxX(); x++) {

				// Build the z/x directory
				File xDirectory = new File(zDirectory, String.valueOf(x));

				for (long y = tileGrid.getMinY(); y <= tileGrid.getMaxY(); y++) {

					GeoPackageTile geoPackageTile = retriever.getTile((int) x,
							(int) y, zoomLevel);

					if (geoPackageTile != null) {

						// Get the y file name for the specified format
						long yFileName = y;
						if (tileType == TileFormatType.TMS) {
							yFileName = TileBoundingBoxUtils
									.getYAsOppositeTileFormat(zoomLevel,
											(int) y);
						}

						File imageFile = new File(xDirectory,
								String.valueOf(yFileName) + "." + imageFormat);

						// Make any needed directories for the image
						xDirectory.mkdirs();

						if (geoPackageTile.getImage() != null) {
							// Write the image to the file
							ImageIO.write(geoPackageTile.getImage(),
									imageFormat, imageFile);
						} else {
							// Write the raw image bytes to the file
							FileOutputStream fos = new FileOutputStream(
									imageFile);
							fos.write(geoPackageTile.getData());
							fos.close();
						}

						zoomCount++;

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

				}
			}

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

			tileCount += zoomCount;
		}

		return tileCount;
	}
1325688
public static boolean write(Image image, String imageType, ImageOutputStream destImageStream) throws IORuntimeException {
		return write(image, imageType, destImageStream, 1);
	}
687973
def tilelayer_preview(tilelayer):
    
    output = '<img src="{src}" alt="{alt}" title="{title}" />'
    url = tilelayer.url_template.format(s="a", z=9, x=265, y=181)
    output = output.format(src=url, alt=tilelayer.name, title=tilelayer.name)
    return output
738355
public static TileColumn createTileDataColumn(int index) {
		return new TileColumn(index, TileTable.COLUMN_TILE_DATA,
				GeoPackageDataType.BLOB, null, true, null, false);
	}
710587
private static void printUsage() {
		System.out.println();
		System.out.println("USAGE");
		System.out.println();
		System.out.println("\t[" + ARGUMENT_PREFIX + ARGUMENT_IMAGE_FORMAT
				+ " image_format] [" + ARGUMENT_PREFIX + ARGUMENT_RAW_IMAGE
				+ "] input_directory tile_type geopackage_file tile_table");
		System.out.println();
		System.out.println("DESCRIPTION");
		System.out.println();
		System.out
				.println("\tReads a tile set from the file system in a z/x/y folder system into a new table in a new or existing GeoPackage file");
		System.out.println();
		System.out.println("ARGUMENTS");
		System.out.println();
		System.out.println("\t" + ARGUMENT_PREFIX + ARGUMENT_IMAGE_FORMAT
				+ " image_format");
		System.out
				.println("\t\tStorage image format in the GeoPackage: png, jpg, jpeg (default is '"
						+ DEFAULT_IMAGE_FORMAT + "')");
		System.out.println();
		System.out.println("\t" + ARGUMENT_PREFIX + ARGUMENT_RAW_IMAGE);
		System.out
				.println("\t\tUse the raw image bytes, only works when combining and cropping is not required. Not compatible with image_format");
		System.out.println();
		System.out.println("\tinput_directory");
		System.out
				.println("\t\tinput directory containing the tile image set used to create the GeoPakage tiles");
		System.out.println();
		System.out.println("\ttile_type");
		System.out
				.println("\t\tTile input format specifying z/x/y folder organization: "
						+ TileFormatType.GEOPACKAGE.name().toLowerCase()
						+ ", "
						+ TileFormatType.STANDARD.name().toLowerCase()
						+ ", "
						+ TileFormatType.TMS.name().toLowerCase());
		System.out
				.println("\t\t\t"
						+ TileFormatType.GEOPACKAGE.name().toLowerCase()
						+ " - x and y represent GeoPackage Tile Matrix width and height. Requires a input_directory/"
						+ TileProperties.GEOPACKAGE_PROPERTIES_FILE + " file");
		System.out.println("\t\t\t"
				+ TileFormatType.STANDARD.name().toLowerCase()
				+ " - x and y origin is top left (Google format)");
		System.out.println("\t\t\t" + TileFormatType.TMS.name().toLowerCase()
				+ " - (Tile Map Service) x and y origin is bottom left");
		System.out.println();
		System.out.println("\tgeopackage_file");
		System.out
				.println("\t\tpath to the GeoPackage file to create or add a new tile table to");
		System.out.println();
		System.out.println("\ttile_table");
		System.out
				.println("\t\tnew tile table name to create within the GeoPackage file");
		System.out.println();
		System.out.println("GEOPACKAGE PROPERTIES");
		System.out.println();
		System.out
				.println("\tReading tiles with a tile_type of geopackage requires a properties file located at: input_directory/"
						+ TileProperties.GEOPACKAGE_PROPERTIES_FILE);
		System.out.println();
		System.out.println("\tRequired Properties:");
		System.out.println();
		System.out.println("\t\t" + TileProperties.GEOPACKAGE_PROPERTIES_EPSG
				+ "=");
		System.out.println("\t\t" + TileProperties.GEOPACKAGE_PROPERTIES_MIN_X
				+ "=");
		System.out.println("\t\t" + TileProperties.GEOPACKAGE_PROPERTIES_MAX_X
				+ "=");
		System.out.println("\t\t" + TileProperties.GEOPACKAGE_PROPERTIES_MIN_Y
				+ "=");
		System.out.println("\t\t" + TileProperties.GEOPACKAGE_PROPERTIES_MAX_Y
				+ "=");
		System.out.println();
		System.out.println("\tOptional Properties:");
		System.out.println();
		System.out
				.println("\t\tIf the file structure is fully populated and represents the matrix width and height, the properties can be omitted.");
		System.out
				.println("\t\tIf a non top zoom level matrix width and height increase by a factor of 2 with each zoom level, the properties can be omitted for those zoom levels.");
		System.out.println();
		System.out.println("\t\t"
				+ TileProperties.getMatrixWidthProperty("{zoom}") + "=");
		System.out.println("\t\t"
				+ TileProperties.getMatrixHeightProperty("{zoom}") + "=");
		System.out.println();

	}
791288
public void setData(BufferedImage image, String imageFormat, Float quality)
			throws IOException {
		setData(ImageUtils.writeImageToBytes(image, imageFormat, quality));
	}
868023
def _write(self, img_array, verbose=False, **kwargs):
        
        if re.match("0|1.[0-4]", version.openjpeg_version) is not None:
            msg = ("You must have at least version 1.5 of OpenJPEG "
                   "in order to write images.")
            raise RuntimeError(msg)

        self._determine_colorspace(**kwargs)
        self._populate_cparams(img_array, **kwargs)

        if opj2.OPENJP2 is not None:
            self._write_openjp2(img_array, verbose=verbose)
        else:
            self._write_openjpeg(img_array, verbose=verbose)
1328969
public void formatWriter(File templateDir, String templateName,
			Object aBindMap, String dateFormat, Writer writer)
			throws IOException, FormatException
	{
		// TODO Auto-generated method stub

	}
977792
public void writeHeader(OutputStreamCounter os) throws IOException {
		if (appendmode) {
			os.write(HEADER[0]);
		}
		else {
			os.write(HEADER[1]);
			os.write(getVersionAsByteArray(header_version));
			os.write(HEADER[2]);
			headerWasWritten = true;
		}
	}
377946
public static void writeJpg(Image image, OutputStream out) throws IORuntimeException {
		write(image, IMAGE_TYPE_JPG, out);
	}
385350
@Override
	public void writeHeader(OutputStream os) throws IOException {
		os.write(ascii("Content-Type: " + mime + "\r\n"));
		os.write(ascii("Content-Length: " + String.valueOf(content.length) + "\r\n"));
	}
931572
public static TileRendererLayer createTileRendererLayer(
            TileCache tileCache, IMapViewPosition mapViewPosition,
            MapDataStore mapFile, XmlRenderTheme renderTheme) {
        TileRendererLayer tileRendererLayer = new TileRendererLayer(tileCache, mapFile,
                mapViewPosition, AndroidGraphicFactory.INSTANCE);
        tileRendererLayer.setXmlRenderTheme(renderTheme);
        return tileRendererLayer;
    }
77681
public synchronized void addTilesInBatch( List<Tile> tilesList ) throws Exception {
        database.execOnConnection(connection -> {
            boolean autoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            try (IHMPreparedStatement pstmt = connection.prepareStatement(insertTileSql);) {
                for( Tile tile : tilesList ) {
                    pstmt.setInt(1, tile.z);
                    pstmt.setInt(2, tile.x);
                    pstmt.setInt(3, tile.y);
                    pstmt.setBytes(4, tile.imageBytes);
                    pstmt.addBatch();
                }
                pstmt.executeBatch();
                return "";
            } finally {
                connection.setAutoCommit(autoCommit);
            }
        });
    }
1181622
private ArrayList<Integer> writeTileData(IFD ifd) throws IOException {
    ArrayList<Integer> newTileOffsets = new ArrayList<Integer>();
    IfdTags metadata = ifd.getMetadata();
    TagValue tileOffsets = metadata.get(324);
    TagValue tileSizes = metadata.get(325);
    for (int i = 0; i < tileOffsets.getCardinality(); i++) {
      int pos = (int) data.position();
      if (pos % 2 != 0) {
        // Correct word alignment
        data.put((byte) 0);
        pos = (int) data.position();
      }
      newTileOffsets.add(pos);
      this.input.seekOffset(tileOffsets.getValue().get(i).toInt());
      for (int j = 0; j < tileSizes.getValue().get(i).toInt(); j++) {
        byte v = this.input.readDirectByte();
        data.put(v);
      }
      if (data.position() % 2 != 0) {
        // Correct word alignment
        data.put((byte) 0);
      }
    }
    return newTileOffsets;
  }
260537
def draw_tiling(coord_generator, filename):
    """"""
    im = Image.new('L', size=(CANVAS_WIDTH, CANVAS_HEIGHT))
    for shape in coord_generator(CANVAS_WIDTH, CANVAS_HEIGHT):
        ImageDraw.Draw(im).polygon(shape, outline='white')
    im.save(filename)
875477
public void write(DataOutput out) throws IOException {
    out.writeInt(getLayoutVersion());
    out.writeInt(getNamespaceID());
    out.writeLong(getCTime());
    out.writeLong(mostRecentCheckpointTxId);
    out.writeLong(curSegmentTxId);
    imageDigest.write(out);
  }
631767
private void createImageAndGraphics(int layer) {
		layeredImage[layer] = new BufferedImage(tileWidth, tileHeight,
				BufferedImage.TYPE_INT_ARGB);
		layeredGraphics[layer] = layeredImage[layer].createGraphics();
		layeredGraphics[layer].setRenderingHint(
				RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
	}