Hello-    I have attached a minor update to the saveImage function posted here:

http://docs.geotools.org/latest/userguide/library/render/gtrenderer.html

The updated code does 2 things:
(1) Sets the correct aspect ratio for maps with projections that use 
easting,northing (vs x,y) like EPSG:4326
(2) Uses the viewport extents of the map if it has been set. Otherwise, uses 
the map extents. 

For your consideration...

Thanks,Peter
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.getViewport().getBounds();

      //If the viewport bounds are not set, set bounds to map extents
        if (mapBounds.getMaxX()==-1) mapBounds = map.getMaxBounds();


        double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0);
        
      //If the axis order is y,x (e.g. lat,lon) modify the aspect ratio
        if 
(mapBounds.getCoordinateReferenceSystem().getCoordinateSystem().getAxis(0).getDirection().equals(AxisDirection.NORTH)){
            heightToWidth = mapBounds.getSpan(0) / mapBounds.getSpan(1);
        }
        
        
        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, "jpeg", fileToSave);

    } catch (java.io.IOException e) {
        throw new RuntimeException(e);
    }
}
------------------------------------------------------------------------------
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration & more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=164703151&iu=/4140/ostg.clktrk
_______________________________________________
GeoTools-GT2-Users mailing list
GeoTools-GT2-Users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/geotools-gt2-users

Reply via email to