I am trying to convert feature collection GeoJSON into image. I want to use geotools to convert. I tested the soultion from this post here. But I am really noob that I ran into some errors like this:
Exception in thread "main" java.lang.IllegalArgumentException: Width (1000) and height (0) cannot be <= 0.
When I print the features.getBounds() it produces this result:
features ReferencedEnvelope[0.0 : -1.0, 0.0 : -1.0] Why is
features.getBounds
is not producing the correct result instead of 0? What should be the correct result?
This is the complete code:
URL states = new URL("http://geojson.xyz/naturalearth-3.3.0/ne_110m_admin_1_states_provinces.geojson");
FeatureJSON featureJSON = new FeatureJSON();
FeatureCollection features = featureJSON.readFeatureCollection(states.openStream());
MapContent mapContent = new MapContent();
mapContent.setTitle("Quickstart");
File outputFile = new File("states.png");
ImageOutputStream outputImageFile = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(outputFile);
outputImageFile = ImageIO.createImageOutputStream(fileOutputStream);
int w = 1000;
ReferencedEnvelope bounds = features.getBounds();
int h = (int) (w * (bounds.getHeight() / bounds.getWidth()));
BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();
mapContent.getViewport().setMatchingAspectRatio(true);
mapContent.getViewport().setScreenArea(new Rectangle(Math.round(w), Math.round(h)));
mapContent.getViewport().setBounds(bounds);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Rectangle outputArea = new Rectangle(w, h);
GTRenderer renderer = new StreamingRenderer();
LabelCacheImpl labelCache = new LabelCacheImpl();
Map<Object, Object> hints = renderer.getRendererHints();
if (hints == null) {
hints = new HashMap<>();
}
hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
renderer.setRendererHints(hints);
renderer.setMapContent(mapContent);
renderer.paint(g2d, outputArea, bounds);
ImageIO.write(bufferedImage, "png", outputImageFile);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputImageFile != null) {
outputImageFile.flush();
outputImageFile.close();
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
log.error("cannot produce image");
}
}
}
Where am I getting this wrong? I just need to convert to get image. I would be happy if there is any other solution too. I need to use Java library so geotools is the best I found.