Fixed stretched image issue on exporting via WMS

This commit is contained in:
Francesco Mangiacrapa 2023-12-15 15:06:28 +01:00
parent 50d1929bfb
commit 32d4fe5672
6 changed files with 600 additions and 64 deletions

21
pom.xml
View File

@ -53,6 +53,15 @@
</dependencies>
</dependencyManagement>
<!-- <repositories>
<repository>
<id>GeoSolutions</id>
<url>http://maven.geo-solutions.it/</url>
</repository>
</repositories> -->
<dependencies>
<dependency>
@ -110,6 +119,18 @@
<scope>provided</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.gdal</groupId> -->
<!-- <artifactId>gdal</artifactId> -->
<!-- <version>3.8.0</version> -->
<!-- </dependency> -->
<!-- <dependency>
<groupId>it.geosolutions</groupId>
<artifactId>geoserver-manager</artifactId>
<version>1.7.0</version>
</dependency>
-->
<dependency>
<groupId>org.gcube.spatial.data</groupId>
<artifactId>geo-utility</artifactId>

View File

@ -0,0 +1,73 @@
package org.gcube.application.geoportaldatamapper.exporter;
import org.gcube.spatial.data.geoutility.shared.BBOX;
public class BBOXConverter {
Integer[] size = new Integer[2];
Double[] bbox = new Double[4];
public static class BBOXPixel {
public double x;
public double y;
public double w;
public double h;
public BBOXPixel(double x, double y, double w, double h) {
super();
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BBOXPixel [x=");
builder.append(x);
builder.append(", y=");
builder.append(y);
builder.append(", w=");
builder.append(w);
builder.append(", h=");
builder.append(h);
builder.append("]");
return builder.toString();
}
}
public static BBOXConverter.BBOXPixel convertToPixel(Integer[] size, Double[] bbox) {
double dw = 1. / size[0];
double dh = 1. / size[1];
double x = (bbox[0] + bbox[1]) / 2.0;
double y = (bbox[2] + bbox[3]) / 2.0;
double w = bbox[1] - bbox[0];
double h = bbox[3] - bbox[2];
x = x * dw;
w = w * dw;
y = y * dh;
h = h * dh;
return new BBOXPixel(x, y, w, h);
}
public static BBOX convertToCoordinate(BBOXPixel bboxP, Integer[] size) {
double h = bboxP.h;
double l = bboxP.x;
double t = bboxP.y;
double w = bboxP.w;
Integer img_w = size[0];
Integer img_h = size[1];
double x1 = l / img_w;
double y1 = t / img_h;
double x2 = (l + w) / img_w;
double y2 = (t + h) / img_h;
return new BBOX(x1, y1, x2, y2, "");
}
}

View File

@ -0,0 +1,100 @@
package org.gcube.application.geoportaldatamapper.exporter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The Class CoordinatesConverter.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 15, 2023
*/
public class CoordinatesConverter {
private static double EARTH_RADIUS = 6378137.0;
/**
* To epsg 3857.
*
* @param coordinates the coordinates as long/lat
* @return the list
*/
public static List<Double> toEpsg3857(List<Double> coordinates) {
double x = Math.toRadians(coordinates.get(0)) * EARTH_RADIUS;
double y = Math.log(Math.tan(Math.PI / 4 + Math.toRadians(coordinates.get(1)) / 2)) * EARTH_RADIUS;
return Arrays.asList(x, y);
}
/**
* To 4326.
*
* @param coordinates the coordinates as long/lat
* @return the list
*/
public static List<Double> to4326(List<Double> coordinates) {
double lat = Math.toDegrees(Math.atan(Math.exp(coordinates.get(1) / EARTH_RADIUS)) * 2 - Math.PI / 2);
double lng = Math.toDegrees(coordinates.get(0) / EARTH_RADIUS);
return Arrays.asList(lng, lat);
}
/**
* To epsg 3857 BBOX.
*
* @param bbox the bbox as long/lat
* @return the string
*/
public static String toEPSG3857_BBOX(String bbox) {
String[] parts = bbox.split(","); // remove spaces and split on ,
double minX = Double.parseDouble(parts[0]);
double minY = Double.parseDouble(parts[1]);
double maxX = Double.parseDouble(parts[2]);
double maxY = Double.parseDouble(parts[3]);
List<Double> l1 = toEpsg3857(Arrays.asList(minX, minY));
List<Double> l2 = toEpsg3857(Arrays.asList(maxX, maxY));
return String.format("%s,%s,%s,%s", l1.get(0), l1.get(1), l2.get(0), l2.get(1));
}
/**
* To EPSG 4326 BBOX.
*
* @param bbox the bbox as long/lat
* @return the string
*/
public static String toEPSG4326_BBOX(String bbox) {
String[] parts = bbox.split(","); // remove spaces and split on ,
double minX = Double.parseDouble(parts[0]);
double minY = Double.parseDouble(parts[1]);
double maxX = Double.parseDouble(parts[2]);
double maxY = Double.parseDouble(parts[3]);
List<Double> l1 = to4326(Arrays.asList(minX, minY));
List<Double> l2 = to4326(Arrays.asList(maxX, maxY));
return String.format("%s,%s,%s,%s", l1.get(0), l1.get(1), l2.get(0), l2.get(1));
}
/**
* Diff B box.
*
* @param bbox the bbox
* @return the array list
*/
public static ArrayList<Double> diffBBox(String bbox) {
String[] parts = bbox.replaceAll("\\s", "").split(","); // remove spaces and split on ,
System.out.println("parts" + " : " + Arrays.asList(parts));
double minX = Double.parseDouble(parts[0]);
double minY = Double.parseDouble(parts[1]);
double maxX = Double.parseDouble(parts[2]);
double maxY = Double.parseDouble(parts[3]);
double width = maxX - minX;
double height = maxY - minY;
ArrayList size = new ArrayList<Double>();
size.add(width);
size.add(height);
return size;
}
}

View File

@ -2,9 +2,11 @@ package org.gcube.application.geoportaldatamapper.exporter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@ -184,7 +186,7 @@ public class Geoportal_PDF_Exporter {
projectTitle = (String) theProjectDV.getTheDocument().getFirstEntryOfMap().getValue();
} catch (Exception e) {
// silent
LOG.trace("Error: ",e);
LOG.trace("Error: ", e);
}
boolean addPageNumber = false;
@ -192,7 +194,7 @@ public class Geoportal_PDF_Exporter {
addPageNumber = Boolean.parseBoolean(pagenumber.getValue());
} catch (Exception e) {
// silent
LOG.trace("Error: ",e);
LOG.trace("Error: ", e);
}
if (addPageNumber) {
@ -207,7 +209,7 @@ public class Geoportal_PDF_Exporter {
addWatermarker = watermarker.getValue();
} catch (Exception e) {
// silent
LOG.trace("Error: ",e);
LOG.trace("Error: ", e);
}
if (addWatermarker != null) {
@ -321,9 +323,9 @@ public class Geoportal_PDF_Exporter {
LOG.info("returning pdf URL: " + pdfFileURL);
// TEST save file locally
// File targetFile = new File(projectTitleSanitized + ".pdf");
// java.nio.file.Files.copy(in, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
// LOG.info("targetFile at: " + targetFile.getAbsolutePath());
File targetFile = new File(projectTitleSanitized + ".pdf");
java.nio.file.Files.copy(in, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
LOG.info("targetFile at: " + targetFile.getAbsolutePath());
IOUtils.closeQuietly(in);
} catch (Exception e) {
@ -336,7 +338,7 @@ public class Geoportal_PDF_Exporter {
pdfDocument.close();
} catch (Exception e) {
// silent
LOG.trace("Error: ",e);
LOG.trace("Error: ", e);
}
}
}
@ -580,7 +582,7 @@ public class Geoportal_PDF_Exporter {
} catch (Exception e) {
// silent
LOG.trace("Error: ",e);
LOG.trace("Error: ", e);
}
//
@ -691,27 +693,25 @@ public class Geoportal_PDF_Exporter {
JsonObject jsonObject = new JsonParser().parse(subDocumentView.getMetadataAsJSON())
.getAsJsonObject();
Table tableContainerL = toTableFixedLayout(document, 1, true);
Table tableMeta = new Table(2);
tableMeta = jsonToTable(tableMeta, 1, "", jsonObject);
List<GCubeSDIViewerLayerDV> layers = subDocumentView.getListLayers();
Table tableI = new Table(2);
if (layers != null) {
for (GCubeSDIViewerLayerDV gCubeLayer : layers) {
tableI.setTextAlignment(TextAlignment.CENTER);
Paragraph pLayer = new Paragraph();
pLayer.setTextAlignment(TextAlignment.CENTER);
Table tableLayer = new Table(1);
tableLayer.setTextAlignment(TextAlignment.CENTER);
Table tableMeta = new Table(2);
tableMeta = jsonToTable(tableMeta, 1, "", jsonObject);
String wmsLink = gCubeLayer.getWMSLink();
LOG.trace("wmsLink(1): " + wmsLink);
wmsLink = URLParserUtil.setValueOfParameter("format", wmsLink, "image/png", true);
String bbox = URLParserUtil.extractValueOfParameterFromURL("bbox", wmsLink);
String wmsVersion = URLParserUtil.extractValueOfParameterFromURL("version", wmsLink);
Integer expWidth = 600;
Integer expHeight = 600;
wmsLink = URLParserUtil.setValueOfParameter("width", wmsLink, expWidth + "", true);
wmsLink = URLParserUtil.setValueOfParameter("height", wmsLink, expHeight + "", true);
Image image = toImageFromLink(wmsLink, null);
LOG.trace("wmsLink cell 1: " + wmsLink);
tableI.addCell(image);
Double expWidth = 500.0;
Double expHeight = 500.0;
BBOX.COORDINATE_FORMAT bboxFormat = wmsVersion.contains("1.3")
? BBOX.COORDINATE_FORMAT.YX
@ -719,7 +719,8 @@ public class Geoportal_PDF_Exporter {
BBOX theBBOX = new BBOX(bbox, bboxFormat);
double bboxOffset = 0.003;
// double bboxOffset = 0.003;
double bboxOffset = 0.01; // no offset
double lowerXR = theBBOX.getLowerLeftX() - bboxOffset;
double lowerYR = theBBOX.getLowerLeftY() - bboxOffset;
double upperXR = theBBOX.getUpperRightX() + bboxOffset;
@ -728,55 +729,69 @@ public class Geoportal_PDF_Exporter {
String parmBBOX = BBOX.toBBOXString(new BBOX(lowerXR, lowerYR, upperXR, upperYR, ""),
bboxFormat);
// Layer with background color
// Calculating bounding box dimension
String bbox3857 = CoordinatesConverter.toEPSG3857_BBOX(parmBBOX);
LOG.debug("toEPSG3857_BBOX: " + bbox3857);
ArrayList<Double> diff = CoordinatesConverter.diffBBox(bbox3857);
LOG.debug("BoudingBox width - height: " + diff);
double width = diff.get(0);
double height = diff.get(1);
double ratio = width / height;
LOG.trace("bbox width: " + width);
LOG.trace("bbox heigth: " + height);
LOG.trace("bbox ratio: " + ratio);
// Calculating width/height ratio
if (ratio > 1) {
expWidth = expWidth * ratio;
} else {
expHeight = expHeight * ratio;
}
int aspectratioWidth = expWidth.intValue();
int aspectratioHeight = expHeight.intValue();
// Layer with aspect ratio on width/height according to bbox width/height
wmsLink = URLParserUtil.setValueOfParameter("width", wmsLink, aspectratioWidth + "",
true);
wmsLink = URLParserUtil.setValueOfParameter("height", wmsLink, aspectratioHeight + "",
true);
String wmsLinkTol = URLParserUtil.setValueOfParameter("bbox", wmsLink, parmBBOX, false);
wmsLinkTol += "&TRANSPARENT=TRUE";
LOG.trace("wmsLink cell 2: " + wmsLink);
LOG.trace("wmsLink aspect ratio link : " + wmsLink);
int maxWidthMap = 350;
Image image2 = toImageFromLink(wmsLinkTol, null, null);
// MapBox static as background
String linkToMapBox = linkToMapBoxStaticMap(parmBBOX, expWidth + "x" + expHeight, sap);
String linkToMapBox = linkToMapBoxStaticMap(parmBBOX,
aspectratioWidth + "x" + aspectratioHeight, sap);
LOG.trace("linkToMapBox: " + linkToMapBox);
Image backImg = toImageFromLink(linkToMapBox, null, null);
Cell mapCell = new Cell();
mapCell.setMaxWidth(maxWidthMap);
mapCell.setNextRenderer(new ImageBackgroundCellRenderer(mapCell, backImg));
mapCell.add(image2);
mapCell.setTextAlignment(TextAlignment.CENTER);
tableI.addCell(mapCell);
tableLayer.addCell(mapCell);
removeBorder(tableLayer);
pLayer.add(tableLayer);
//adding tables with layer and meta to table container
// Row with layers
tableContainerL.addCell(pLayer);
// Row with layer metadata
tableContainerL.addCell(tableMeta);
}
}
PdfFont ho = PdfFontFactory.createFont(StandardFonts.HELVETICA_OBLIQUE);
Paragraph paragraph1 = new Paragraph();
String alert = "(i) The layer preview could be scratched";
if (gisLink != null)
alert += ". See the gis layer at " + gisLink;
else {
// try {
// alert += ". See the gis layer at " + credits.getLinkGnaD4ScienceOrg();
// } catch (Exception e) {
// // TODO: handle exception
// }
}
paragraph1.add(alert);
paragraph1.setFont(bold).setFontSize(6);
paragraph1.setBorder(Border.NO_BORDER);
paragraph1.setFont(ho);
// Row with alert message
tableContainerL.addCell(paragraph1);
// Row with layers
tableContainerL.addCell(tableI);
// Row with layer metadata
tableContainerL.addCell(tableMeta);
// Row with alert message - No more required
// tableContainerL.addCell(paragraph1);
document.add(tableContainerL);
}
@ -984,7 +999,7 @@ public class Geoportal_PDF_Exporter {
} catch (Exception e) {
// silent
LOG.trace("Error: ",e);
LOG.trace("Error: ", e);
}
@ -1017,7 +1032,7 @@ public class Geoportal_PDF_Exporter {
} catch (Exception e) {
// silent
LOG.trace("Error: ",e);
LOG.trace("Error: ", e);
}
return img;

View File

@ -0,0 +1,126 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CoordinatesConverter {
// public static List<Double> epsg4326toEpsg3857(List<Double> coordinates) {
// double x = (coordinates.get(0) * 20037508.34) / 180;
// double y = Math.log(Math.tan(((90 + coordinates.get(1)) * Math.PI) / 360)) / (Math.PI / 180);
// y = (y * 20037508.34) / 180;
// return Arrays.asList(x, y);
// }
// public static String convertBBOXFromEpsg4326toEpsg3857(String bbox) {
// String[] parts = bbox.split(","); // remove spaces and split on ,
// System.out.println("bbox parts: " + bbox);
// double minX = Double.parseDouble(parts[0]);
// double minY = Double.parseDouble(parts[1]);
// double maxX = Double.parseDouble(parts[2]);
// double maxY = Double.parseDouble(parts[3]);
// List<Double> l1 = epsg4326toEpsg3857(Arrays.asList(minX, minY));
// List<Double> l2 = epsg4326toEpsg3857(Arrays.asList(maxX, maxY));
// return String.format("%s,%s,%s,%s", l1.get(0), l1.get(1), l2.get(0), l2.get(1));
// }
// public static LatLng to4326(Wgs84 wgs84) {
// double lat = Math.toDegrees(Math.atan(Math.exp(wgs84.getY() / EARTH_RADIUS)) * 2 - Math.PI/2);
// double lng = Math.toDegrees(wgs84.getX() / EARTH_RADIUS);
// return new LatLng(lat, lng);
// }
private static double EARTH_RADIUS = 6378137.0;
public static List<Double> toEpsg3857(List<Double> coordinates) {
double x = Math.toRadians(coordinates.get(0)) * EARTH_RADIUS;
double y = Math.log(Math.tan(Math.PI / 4 + Math.toRadians(coordinates.get(1)) / 2)) * EARTH_RADIUS;
return Arrays.asList(x, y);
}
public static String toEpsg3857BBOX(String bbox) {
String[] parts = bbox.split(","); // remove spaces and split on ,
System.out.println("bbox parts: " + bbox);
double minX = Double.parseDouble(parts[0]);
double minY = Double.parseDouble(parts[1]);
double maxX = Double.parseDouble(parts[2]);
double maxY = Double.parseDouble(parts[3]);
List<Double> l1 = toEpsg3857(Arrays.asList(minX, minY));
List<Double> l2 = toEpsg3857(Arrays.asList(maxX, maxY));
return String.format("%s,%s,%s,%s", l1.get(0), l1.get(1), l2.get(0), l2.get(1));
}
public static String toEpsg4326BBOX(String bbox) {
String[] parts = bbox.split(","); // remove spaces and split on ,
System.out.println("bbox parts: " + bbox);
double minX = Double.parseDouble(parts[0]);
double minY = Double.parseDouble(parts[1]);
double maxX = Double.parseDouble(parts[2]);
double maxY = Double.parseDouble(parts[3]);
List<Double> l1 = to4326(Arrays.asList(minX, minY));
List<Double> l2 = to4326(Arrays.asList(maxX, maxY));
return String.format("%s,%s,%s,%s", l1.get(0), l1.get(1), l2.get(0), l2.get(1));
}
public static List<Double> to4326(List<Double> coordinates) {
double lat = Math.toDegrees(Math.atan(Math.exp(coordinates.get(1) / EARTH_RADIUS)) * 2 - Math.PI / 2);
double lng = Math.toDegrees(coordinates.get(0) / EARTH_RADIUS);
return Arrays.asList(lng, lat);
}
public static ArrayList<Double> diffBBox(String bbox) {
String[] parts = bbox.replaceAll("\\s", "").split(","); // remove spaces and split on ,
System.out.println("parts" + " : " + Arrays.asList(parts));
double minX = Double.parseDouble(parts[0]);
double minY = Double.parseDouble(parts[1]);
double maxX = Double.parseDouble(parts[2]);
double maxY = Double.parseDouble(parts[3]);
double width = maxX - minX;
double height = maxY - minY;
ArrayList size = new ArrayList<Double>();
size.add(width);
size.add(height);
return size;
}
public static void main(String[] args) {
String bbox = "14.350604,40.632238,14.353074,40.634530";
// String bbox = "12.263867,44.231887,12.345057,44.263416";
String bbox3857 = toEpsg3857BBOX(bbox);
System.out.println("bbox3857: "+bbox3857);
String bbox4326 = toEpsg4326BBOX(bbox3857);
System.out.println("bbox4326: "+bbox4326);
//bbox3857 = "-13888944.635145342,2867630.7173607955,-7451112.364854658,6340929.2826392045";
ArrayList<Double> diff = diffBBox(bbox3857);
System.out.println(diff);
double width = diff.get(0);
double height = diff.get(1);
double ratio = width/height;
// double width = diff.get(0) * 0.90;
// double height = diff.get(1) * 0.90;
System.out.println("width: "+width);
System.out.println("heigth: "+height);
System.out.println("ratio: "+ratio);
double expectedWidth = 500;
double expectedHeight = 500;
if(width>height) {
expectedHeight = expectedWidth * ratio;
}else {
expectedWidth = expectedHeight * ratio;
}
System.out.println("expectedWidth: "+expectedWidth);
System.out.println("expectedHeight: "+expectedHeight);
}
}

View File

@ -2,6 +2,8 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import org.gcube.application.geoportalcommon.geoportal.GeoportalClientCaller;
@ -13,6 +15,7 @@ import org.gcube.application.geoportaldatamapper.reader.ServiceAccessPoint;
import org.gcube.application.geoportaldatamapper.shared.ExporterProjectSource;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.spatial.data.geoutility.shared.BBOX;
import org.junit.Before;
import org.junit.Test;
@ -36,23 +39,25 @@ public class Geoportal_Export_To_PDF_Tests {
private UseCaseDescriptorCaller clientUCD;
private ProjectsCaller clientProjects;
//private static String PROFILE_ID = "concessioni-estere";
// private static String PROFILE_ID = "concessioni-estere";
private static String PROFILE_ID = "profiledConcessioni";
private static String PROJECT_ID = "654e07a75bdd5478cca320c0";
private static String PROJECT_ID = "6388e4f8a1e60e66b7b584ac";
// DEV
// 654e07a75bdd5478cca320c0
// 655489965bdd5478cca320ea
//PROD Concessioni
// PROD Concessioni
// 6388e4f8a1e60e66b7b584ac Ficocle-Cervia Vecchia
// 6388d9b3a1e60e66b7b5843a
// 646353c5d7fb4a4633022803 Villa Romana del Capo di Sorrento
// 63f8c481e9d6ac16f394f1e6
// 638888fba1e60e66b7b581dd
// 650304487814b87373631242 Scavi a Calvatone-Bedriacum
// 6388ea17a1e60e66b7b584dd Indagini archeologiche presso la pieve di San Pietro in Bossolo, Barberino Tavarnelle (FI)
// 6388ea17a1e60e66b7b584dd Indagini archeologiche presso la pieve di San Pietro
// in Bossolo, Barberino Tavarnelle (FI)
// 64537208d7fb4a4633022039 PArCo di Poggio del Molino - Progetto Archeodig
// 638885fea1e60e66b7b581bd Scavo della Grotta della Ciota Ciara
// PRE
// 63d011c4dcac4551b9a6b930
@ -64,7 +69,6 @@ public class Geoportal_Export_To_PDF_Tests {
// PROD concessione-estere
// 64a2c5c6a827c620191599ff
// IMPORTANT!!!! #NB SET USERNAME = null to test PUBLIC ACCESS
private static String USERNAME = null;
@ -96,7 +100,7 @@ public class Geoportal_Export_To_PDF_Tests {
*
* @return the client
*/
//@Before
@Before
public void getClient() {
readContextSettings();
// assumeTrue(GCubeTest.isTestInfrastructureEnabled());
@ -109,7 +113,7 @@ public class Geoportal_Export_To_PDF_Tests {
/**
* API map box service endpoint reader.
*/
//@Test
// @Test
public void apiMapBoxServiceEndpointReader() {
try {
ServiceAccessPoint se = MapBoxEndpointReader.getMapBoxEndpoint();
@ -123,14 +127,14 @@ public class Geoportal_Export_To_PDF_Tests {
/**
* Test read project view.
*/
//@Test
@Test
public void testExportToPDF() {
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
Geoportal_PDF_Exporter pdfExporter = new Geoportal_PDF_Exporter();
ExporterProjectSource exporterSource = new ExporterProjectSource();
//#NB SET USERNAME = null to test PUBLIC ACCESS
// #NB SET USERNAME = null to test PUBLIC ACCESS
USERNAME = "francesco.mangiacrapa";
exporterSource.setAccountname(USERNAME);
exporterSource.setProfileID(PROFILE_ID);
@ -146,4 +150,201 @@ public class Geoportal_Export_To_PDF_Tests {
}
// public static void main(String[] args) {
// GeoServerRESTReader reader = new GeoServerRESTReader("");
//
// RESTLayer layer = reader.getLayer("");
//
// layer.get
//
// }
/*
* public static void main(String[] args) { double imageWidth = 400; double
* imageHeight = 400;
*
* double expansionFactor = 0.1;
*
* String bbox = "8.310868,45.710911,8.310912,45.710940";
*
* BBOX theBBOX = new BBOX(bbox, COORDINATE_FORMAT.XY); // double x = imageWidth
* * theBBOX.getLowerLeftX(); // double y = imageHeight *
* theBBOX.getLowerLeftY() ; // double w = imageWidth *
* theBBOX.getUpperRightX(); // double h = imageHeight *
* theBBOX.getUpperRightY();
*
* Integer[] size = new Integer[2]; size[0] = 400; size[1] = 400; Double[] bboxD
* = new Double[4]; bboxD[0] = theBBOX.getLowerLeftX(); bboxD[1] =
* theBBOX.getLowerLeftY() ; bboxD[2] = theBBOX.getUpperRightX(); bboxD[3] =
* theBBOX.getUpperRightY(); BBOXPixel bboxP =
* BBOXConverter.convertToPixel(size, bboxD);
*
* System.out.println("bboxP: "+bboxP);
*
* double left = Math.max(bboxP.x - bboxP.w * expansionFactor, 0); double top =
* Math.max(bboxP.y - bboxP.h * expansionFactor, 0); double width =
* Math.min(bboxP.x + bboxP.w * 2 * expansionFactor, imageWidth - left); double
* height = Math.min(bboxP.h + bboxP.h * 2 * expansionFactor, imageHeight -
* top);
*
* BBOXPixel bboxP2 = new BBOXPixel(left, top, width, height);
*
* BBOX bboxE = BBOXConverter.convertToCoordinate(bboxP2, size);
* System.out.println(bboxE);
*
* }
*/
static class BoundingBox {
public double north, south, east, west;
public BoundingBox(String location, float km) {
// System.out.println(location + " : "+ km);
String[] parts = location.replaceAll("\\s", "").split(","); // remove spaces and split on ,
System.out.println("parts" + " : " + Arrays.asList(parts));
double lng = Double.parseDouble(parts[0]);
double lat = Double.parseDouble(parts[1]);
double adjust = .008983112; // 1km in degrees at equator.
// adjust = 0.008983152770714983; // 1km in degrees at equator.
// System.out.println("deg: "+(1.0/40075.017)*360.0);
north = lat + (km * adjust);
south = lat - (km * adjust);
double lngRatio = 1 / Math.cos(Math.toRadians(lat)); // ratio for lng size
// System.out.println("lngRatio: "+lngRatio);
east = lng + (km * adjust) * lngRatio;
west = lng - (km * adjust) * lngRatio;
System.out.println(new BBOX(west, south, east, north, ""));
}
}
// public static void main(String[] args) {
// gdal.AllRegister();
//
// DataSource dataSource = ogr.Open("https://geoserver-1.cloud-dev.d4science.org/geoserver/profiledconcessioni_gcube_devsec_devvre_654e07a75bdd5478cca320c0/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image/png&TRANSPARENT=true&STYLES=&LAYERS=profiledconcessioni_gcube_devsec_devvre_654e07a75bdd5478cca320c0:ce19_09&exceptions=application/vnd.ogc.se_inimage&SRS=EPSG:4326&WIDTH=400&HEIGHT=400&BBOX=12.235679626464844,44.179115295410156,12.373008728027344,44.316444396972656");
// Layer layer = dataSource.GetLayer(0);
//
// }
/**
* // TODO Make safe for multiple calls !Not safe on multiple calls as drivers
* are destroyed at the end of the method need so when called with multiple jobs
* chance of issues.
*
* @param geoJson GeoJson string which contain position in degrees for lat
* lon.
* @param output Output file to create tiff.
* @param resX The x resolution of new image
* @param resY The x resolution of new image
* @param burnColor The color which the geojson features will be colored in.
* @param noDataValue The nodata value for geotiff image.
*/
// public void createGeoTiffFromGeoJson(String geoJson, File output, int resX, int resY, Color burnColor, int noDataValue)
// {
// gdal.AllRegister();
// Driver driver = gdal.GetDriverByName("GTiff");
// driver.Register();
//
// DataSource dataSource = ogr.Open(geoJson);
// Layer layer = dataSource.GetLayer(0);
// final Vector<String> imageCreationOptions = new Vector<>(1);
// imageCreationOptions.add("COMPRESS=LZW");
// Dataset newDateSet = driver.Create(output.getAbsolutePath(), resX, resY, 4, gdalconst.GDT_Byte, imageCreationOptions);
// double[] extent = layer.GetExtent();
// double x_res = ((extent[1] - extent[0]) / resX);
// double y_res = ((extent[3] - extent[2]) / resY);
// newDateSet.SetGeoTransform(new double[]
// {
// extent[0], x_res, 0, extent[3], 0, -y_res
// });
// newDateSet.SetProjection("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433],AUTHORITY[\"EPSG\",\"4326\"]]");
// newDateSet.GetRasterBand(1).SetNoDataValue(noDataValue);
// newDateSet.GetRasterBand(2).SetNoDataValue(noDataValue);
// newDateSet.GetRasterBand(3).SetNoDataValue(noDataValue);
// newDateSet.GetRasterBand(4).SetNoDataValue(noDataValue);
// newDateSet.GetRasterBand(1).FlushCache();
// newDateSet.GetRasterBand(2).FlushCache();
// newDateSet.GetRasterBand(3).FlushCache();
// newDateSet.GetRasterBand(4).FlushCache();
// int[] band =
// {
// 1, 2, 3, 4
// };
// double[] burn =
// {
// burnColor.getRed(), burnColor.getGreen(), burnColor.getBlue(), burnColor.getAlpha()
// };
// gdal.RasterizeLayer(newDateSet, band, layer, burn);
// driver.Deregister();
// org.gdal.gdal.gdal.GDALDestroyDriverManager();
// }
//
// public static void main(String[] args) {
//
// String location = "16.440317,40.072127,16.451167,40.082117";
//
// // EXTENT minx miny maxx maxy
// // EXTENT west south east north
//
// double minX = 12.263867;
// double minY = 44.231887;
// double maxX = 12.345057;
// double maxY = 44.263416;
//
// // public double north, south, east, west;
// // min
// String location = minX + "," + minY;
//
// new BoundingBox(location, 1);
//
// // max
// location = maxX + "," + maxY;
//
// new BoundingBox(location, 1);
// }
// Mercator projection
public static ArrayList<Double> convertToPixel(double lng, double lat, double mapWidth, double mapHeight) {
// get x
double x = (lng + 180) * (mapWidth / 360);
// convert from degrees to radians
double latRad = lat * Math.PI / 180;
// get y value
double mercN = Math.log(Math.tan((Math.PI / 4) + (latRad / 2)));
double y = (mapHeight / 2) - (mapWidth * mercN / (2 * Math.PI));
ArrayList size = new ArrayList<Double>();
size.add(x);
size.add(y);
return size;
}
public static ArrayList<Double> convertPixed(double lng, double lat, double mapWidth, double mapHeight) {
// get x
double x = (lng * mapWidth) / 360;
double y = (lat * mapHeight) / 180;
ArrayList size = new ArrayList<Double>();
size.add(x);
size.add(y);
return size;
}
public static Double[] epsg4326toEpsg3857(Double[] coordinates) {
double x = (coordinates[0] * 20037508.34) / 180;
double y = Math.log(Math.tan(((90 + coordinates[1]) * Math.PI) / 360)) / (Math.PI / 180);
y = (y * 20037508.34) / 180;
Double[] xy = new Double[2];
xy[0] = x;
xy[1] = y;
return xy;
}
}