将缩放图像级别保存到文件

save zoom image level to file

假设我要加载一个 shp 文件,在其中执行我的操作并将地图另存为图像。

为了保存我正在使用的图像:

public void saveImage(final MapContent map, final String file, final int imageWidth) {

      GTRenderer renderer = new StreamingRenderer();
      renderer.setMapContent(map);

      Rectangle imageBounds = null;
      ReferencedEnvelope mapBounds = null;

      try {
          mapBounds = map.getMaxBounds();
          double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0);
          imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth));
      } catch (Exception e) {
          // Failed to access map layers
          throw new RuntimeException(e);
      }

      BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB);
      Graphics2D gr = image.createGraphics();
      gr.setPaint(Color.WHITE);
      gr.fill(imageBounds);

      try {
          renderer.paint(gr, imageBounds, mapBounds);
          File fileToSave = new File(file);
          ImageIO.write(image, "png", fileToSave);
      } catch (IOException e) {
          throw new RuntimeException(e);
      }
  }

但是,假设我正在做这样的事情:

...
MapContent map = new MapContent();
map.setTitle("TEST");
map.addLayer(layer);
map.addLayer(shpLayer);

// zoom into the line
MapViewport viewport = new MapViewport(featureCollection.getBounds());
map.setViewport(viewport);

saveImage(map, "/tmp/img.png", 800);

1) 问题是缩放级别没有保存在图像上 file.Is 有办法保存吗?

2) 当我做的时候 MapViewport(featureCollection.getBounds()); 有没有办法稍微扩展边界以获得更好的视觉表现?

...

您没有在当前缩放级别保存地图的原因是在您的 saveImage 方法中有一行:

mapBounds = map.getMaxBounds();

始终使用地图的全图,您可以将其更改为

mapBounds = map.getViewport().getBounds();

您可以通过以下方式扩展边界框:

    ReferencedEnvelope bounds = featureCollection.getBounds();
    double delta = bounds.getWidth()/20.0; //5% on each side
    bounds.expandBy(delta );
    MapViewport viewport = new MapViewport(bounds);
    map.setViewport(viewport );

从 GUI 保存地图的一种更快(更容易)的方法是使用这样的方法,它只保存屏幕上的内容:

public void drawMapToImage(File outputFile, String outputType,
        JMapPane mapPane) {
    ImageOutputStream outputImageFile = null;
    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(outputFile);
        outputImageFile = ImageIO.createImageOutputStream(fileOutputStream);
        RenderedImage bufferedImage = mapPane.getBaseImage();
        ImageIO.write(bufferedImage, outputType, outputImageFile);
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (outputImageFile != null) {
                outputImageFile.flush();
                outputImageFile.close();
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        } catch (IOException e) {// don't care now
        }
    }
}