GIS
geotiff to png, geotiff get extent, shp to geojson, java
degulv
2020. 1. 16. 17:08
반응형
package hello;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.coverage.grid.io.GridCoverage2DReader;
import org.geotools.coverage.grid.io.GridFormatFinder;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.filter.text.cql2.CQLException;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.geometry.Envelope;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
public class TestGeoTools {
/**
* GeoTIFF to PNG 변경
*
* @param sourceFilePath
* @param targetFilePath
* @return boolean
* @throws IOException
*/
public static boolean convertGeoTiffToPng(String sourceFilePath, String targetFilePath) throws IOException {
File file = new File(sourceFilePath);
if (!file.exists()) {
System.out.println("file not found");
return false;
}
// AbstractGridFormat format = GridFormatFinder.findFormat(file);
// System.out.println(format.getName());
BufferedImage img = ImageIO.read(file);
int width = img.getWidth();
int height = img.getHeight();
Raster raster = img.getData();
int bands = raster.getNumBands();
System.out.println("raster bands: " + bands);
BufferedImage saveimage = null;
WritableRaster dest = null;
switch (bands) {
case 1:
saveimage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
saveimage.createGraphics().drawImage(img, 0, 0, Color.white, null);
break;
case 3:
// Create an identically-sized output raster
dest = raster.createCompatibleWritableRaster();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// Copy the pixel
double[] pixel = new double[bands];
pixel = raster.getPixel(x, y, pixel);
if (pixel[0] > 255 && pixel[0] > 255 && pixel[0] > 255) {
pixel[0] = 255;
pixel[1] = 255;
pixel[2] = 255;
}
dest.setPixel(x, y, pixel);
}
}
// Save the raster back to the Image
saveimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
saveimage.setData(dest);
break;
case 4:
// Create an identically-sized output raster
dest = raster.createCompatibleWritableRaster();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// Copy the pixel
double[] pixel = new double[bands];
pixel = raster.getPixel(x, y, pixel);
dest.setPixel(x, y, pixel);
}
}
// Save the raster back to the Image
saveimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
saveimage.setData(dest);
break;
}
// Write the new file
ImageIO.write(saveimage, "png", new File(targetFilePath));
return true;
}
/**
* GeoTIFF 에서 Extent값 가져옴
*
* @param sourceFilePath
* @return extent
* @throws IOException
*/
public static double[] getExtentFromGeoTiff(String sourceFilePath) throws IOException {
File file = new File(sourceFilePath);
AbstractGridFormat format = GridFormatFinder.findFormat(file);
GridCoverage2DReader reader = format.getReader(file);
GridCoverage2D coverage = (GridCoverage2D) reader.read(null);
Envelope env = coverage.getEnvelope();
double minX = env.getLowerCorner().getOrdinate(0);
double minY = env.getLowerCorner().getOrdinate(1);
double maxX = env.getUpperCorner().getOrdinate(0);
double maxY = env.getUpperCorner().getOrdinate(1);
System.out.println("getGeoTiffExtent=" + coverage.getCoordinateReferenceSystem2D().getName().toString() + " " + coverage.getName() + ": " + minX + "," + minY + " " + maxX + "," + maxY);
double[] extent = new double[4];
extent[0] = minX;
extent[1] = minY;
extent[2] = maxX;
extent[3] = maxY;
return extent;
}
/**
* SHP파일에서 GeoJson가져옴
*
* @param shpFilePath
* @param charset
* @param mapEPSG
* @param bbox
* @return geojson string
* @throws IOException
* @throws NoSuchAuthorityCodeException
* @throws FactoryException
* @throws TransformException
* @throws CQLException
*/
public static String getGeoJsonFromShp(String shpFilePath, String charset, String mapEPSG, String bbox)
throws IOException,
NoSuchAuthorityCodeException,
FactoryException,
TransformException,
CQLException {
// 파일 읽기
File file = new File(shpFilePath);
Map < String,
Object > map = new HashMap < >();
map.put("url", file.toURI().toURL());
map.put("create spatial index", true);
map.put("charset", charset); // encode
System.out.println("charset::" + charset);
DataStore dataStore = DataStoreFinder.getDataStore(map);
String typeName = dataStore.getTypeNames()[0];
FeatureSource < SimpleFeatureType,
SimpleFeature > source = dataStore.getFeatureSource(typeName);
CRSAuthorityFactory factory = CRS.getAuthorityFactory(true);
CoordinateReferenceSystem mapCRS = factory.createCoordinateReferenceSystem(mapEPSG); // CRS.decode(srsName);
CoordinateReferenceSystem srcCRS = dataStore.getSchema(typeName).getCoordinateReferenceSystem();
System.out.println("dataCRS.toWKT() :: " + srcCRS.toWKT());
System.out.println("mapCRS.toWKT() :: " + mapCRS.toWKT());
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform(mapCRS, srcCRS, lenient);
String[] bbox_str = bbox.split(",");
double[] param_bbox = new double[4];
param_bbox[0] = Double.parseDouble(bbox_str[0]);
param_bbox[1] = Double.parseDouble(bbox_str[1]);
param_bbox[2] = Double.parseDouble(bbox_str[2]);
param_bbox[3] = Double.parseDouble(bbox_str[3]);
double[] srcProjec1 = {
param_bbox[0],
param_bbox[1]
}; // easting, northing,
double[] srcProjec2 = {
param_bbox[2],
param_bbox[3]
}; // easting, northing,
double[] dstProjec1 = {
0,
0
};
double[] dstProjec2 = {
0,
0
};
transform.transform(srcProjec1, 0, dstProjec1, 0, 1);
transform.transform(srcProjec2, 0, dstProjec2, 0, 1);
String filter_bbox = dstProjec1[0] + "," + dstProjec1[1] + "," + dstProjec2[0] + "," + dstProjec2[1];
System.out.println("filter_bbox: " + filter_bbox);
Filter filter = Filter.INCLUDE; // ECQL.toFilter("BBOX(THE_GEOM, 10,20,30,40)")
if (!filter_bbox.isEmpty()) {
filter = ECQL.toFilter("BBOX(the_geom," + filter_bbox + ")"); // ECQL.toFilter("BBOX(THE_GEOM,
// 10,20,30,40)")
}
FeatureCollection < SimpleFeatureType,
SimpleFeature > collection = source.getFeatures(filter);
FeatureJSON featureJson = new FeatureJSON();
StringWriter writer = new StringWriter();
featureJson.writeFeatureCollection(collection, writer);
String geojson = writer.toString();
return geojson;
}
}
반응형