gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:42:12 24 4
gpt4 key购买 nike

假设我想加载一个 shp 文件,对其进行处理并将 map 保存为图像。

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

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) 问题是缩放级别没有保存在图像文件中。有办法保存吗?

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

...

最佳答案

您没有以当前缩放级别保存 map 的原因是在您的 saveImage 方法中您有以下行:

mapBounds = map.getMaxBounds();

始终使用 map 的完整范围,您可以将其更改为

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 保存 map 的一种更快(更简单)的方法是使用这样的方法,该方法仅准确保存屏幕上的内容:

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
}
}
}

关于java - 将缩放图像级别保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45277924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com