数据准备
1.若干shp文件及类型 shplist
2.打印坐标范围bbox
3.图片宽高height、width
4.导出图片路径outimgpath
5.点线面sld样式文件(点击可下载)
{mapexportparam:{bbox: [104, 40, 112, 31],height: 1024,width: 1024},
outimgpath: "D:/gisdata/gp/bbb.png",
shplist: [{filepath:"D:/gisdata/gp/city.shp", type: "poylgon"}]
}
代码
private static void exportImage(List<Map<String, Object>> shplist,Map<String, Object> mapexportparam:,String outimgpath) {
for (Map<String, Object> mapp : shplistlist) {
addShapeLayer(mapp.get("filepath").toString(),"src/main/resources/template/"+mapp.get("type").toString()+"style.sld");
}
getMapContent(mapexportparam:,outimgpath);
}
public static void addShapeLayer(String shpPath, String sldPath) {
try {
File file = new File(shpPath);
ShapefileDataStore shpDataStore = null;
shpDataStore = new ShapefileDataStore(file.toURI().toURL());
// 设置编码
Charset charset = Charset.forName("GBK");
shpDataStore.setCharset(charset);
String typeName = shpDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = null;
featureSource = shpDataStore.getFeatureSource(typeName);
// SLD的方式
File sldFile = new File(sldPath);
StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory();
SLDParser stylereader = new SLDParser(styleFactory, sldFile.toURI().toURL());
Style[] stylearray = stylereader.readXML();
Style style = stylearray[0];
// 默认的方式
// Style style = SLD.createSimpleStyle(featureSource.getSchema());
// SLD.setPolyColour(style, Color.RED );
Layer layer = new FeatureLayer(featureSource, style);
map.addLayer(layer);
} catch (Exception e) {
e.printStackTrace();
}
}
// 导出地图
public static void getMapContent(Map<String,Object> paras, String imgPath) {
try {
double[] bbox = (double[]) paras.get("bbox");
double x1 = bbox[0], y1 = bbox[1], x2 = bbox[2], y2 = bbox[3];
int width = (int) paras.get("width"), height = (int) paras.get("height");
// 设置输出范围
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
ReferencedEnvelope mapArea = new ReferencedEnvelope(x1, x2, y1, y2, crs);
// 初始化渲染器
StreamingRenderer sr = new StreamingRenderer();
sr.setMapContent(map);
// 初始化输出图像
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Rectangle rect = new Rectangle(0, 0, width, height);
// 绘制地图
sr.paint((Graphics2D) g, rect, mapArea);
// 将BufferedImage变量写入文件中。
ImageIO.write(bi, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}