/**
  * @param node
  * @return minimum x coordinate
  * @throws GeometryException
  */
 public static String getXMin(Node node) throws GeometryException {
   if (node == null) {
     return "";
   }
   Geometry geometry = GMLGeometryAdapter.wrap((Element) node, null);
   Envelope envelope = geometry.getEnvelope();
   return Double.toString(envelope.getMin().getX());
 }
 /**
  * @param node
  * @return minimum z coordinate
  * @throws GeometryException
  */
 public static String getZMax(Node node) throws GeometryException {
   if (node == null) {
     return "";
   }
   Geometry geometry = GMLGeometryAdapter.wrap((Element) node, null);
   Envelope envelope = geometry.getEnvelope();
   if (geometry.getCoordinateDimension() > 2) {
     return "";
   }
   return Double.toString(envelope.getMax().getZ());
 }
  /**
   * returns the region of the source image that intersects with the GridCoverage to be created as
   * Rectangle as well as the Envelope of the region in the native CRS and the LonLatEnvelope of
   * this region. For ECW files these values reflect exactly the desired result, as the library will
   * cut and sample the source image during read.
   *
   * @param reqwidth width of the requested region
   * @param reqheight height of the requested region
   * @return the region of the source image that intersects with the GridCoverage to be created as
   *     Rectangle as well as the Envelope of the region in the native CRS and the LonLatEnvelope of
   *     this region.
   */
  private Object[] getECWImageRegion(int reqwidth, int reqheight) {

    Envelope imgenvelope = getLLEAsEnvelope();
    Envelope dstenvelope = envelope.createIntersection(imgenvelope);

    // In case of ECW files, we calculate the rectangle according
    // to the desired result, not according to the source image,
    // as clipping and sampling will be done by the ECW library.
    // Hence dstenvelope and srcenvelope are the same and width/height
    // must be clipped with our grid-cell (if necessary).
    double dWidth = (dstenvelope.getWidth() * reqwidth) / envelope.getWidth();
    double dHeight = (dstenvelope.getHeight() * reqheight) / envelope.getHeight();
    return calcRegionRectangle(dstenvelope, dstenvelope, dWidth, dHeight);
  }
Ejemplo n.º 4
0
 /**
  * Appends the XML representation of the given <code>Envelope</code> (as WGS84BoundingBoxType[])
  * to the passed <code>Element</code>.
  *
  * @param root
  * @param envelope
  */
 public static void appendWgs84BoundingBox(Element root, Envelope envelope) {
   LOG.entering();
   Element wgs84BoundingBoxElement = XMLTools.appendElement(root, OWS, "ows:WGS84BoundingBox");
   XMLTools.appendElement(
       wgs84BoundingBoxElement,
       OWS,
       "ows:LowerCorner",
       envelope.getMin().getX() + " " + envelope.getMin().getY());
   XMLTools.appendElement(
       wgs84BoundingBoxElement,
       OWS,
       "ows:UpperCorner",
       envelope.getMax().getX() + " " + envelope.getMax().getY());
   LOG.exiting();
 }
  /**
   * renders one point to the submitted graphic context considering the also submitted projection
   *
   * @param g
   * @param point
   * @param projection
   * @param image
   * @param dis displacement
   */
  private void drawPoint(
      Graphics2D g, Point point, GeoTransform projection, Image image, double[] dis) {
    Envelope destSize = projection.getDestRect();
    Position source = point.getPosition();
    int x = (int) Math.round(projection.getDestX(source.getX()) + 0.5 + dis[0]);
    int y = (int) Math.round(projection.getDestY(source.getY()) + 0.5 + dis[1]);

    int x_ = x - (image.getWidth(null) >> 1);
    int y_ = y - (image.getHeight(null) >> 1);

    int dx = Math.min(image.getWidth(null), (int) destSize.getWidth() - x_);
    int dy = Math.min(image.getHeight(null), (int) destSize.getHeight() - y_);
    int tx = Math.min((int) destSize.getWidth(), x_ + image.getWidth(null));
    int ty = Math.min((int) destSize.getHeight(), y_ + image.getHeight(null));

    g.drawImage(image, x_, y_, tx, ty, 0, 0, dx, dy, null);
  }
  /**
   * returns the minimum coordinate of the envelope of the geometry encoded by the passed node as a
   * double array
   *
   * @param node
   * @return the minimum coordinate of the envelope of the geometry encoded by the passed node as a
   *     double array
   * @throws GeometryException
   */
  public static String getMaxAsArray(Node node) throws GeometryException {
    if (node == null) {
      return "";
    }
    Geometry geometry = GMLGeometryAdapter.wrap((Element) node, null);
    if (geometry instanceof Point) {
      return "";
    }
    Envelope env = geometry.getEnvelope();
    StringBuffer sb = new StringBuffer(100);

    Position pos = env.getMax();
    int dim = pos.getCoordinateDimension();
    double[] d = pos.getAsArray();
    for (int i = 0; i < dim - 1; i++) {
      sb.append(Double.toString(d[i])).append(' ');
    }
    sb.append(Double.toString(d[dim - 1]));

    return sb.toString();
  }
  /**
   * Calculate the rectangle that belongs to the given destination envelope in the given source
   * image.
   */
  private Object[] calcRegionRectangle(
      Envelope dstenv, Envelope srcenv, double srcwidth, double srcheight) {
    GeoTransform gt =
        new WorldToScreenTransform(
            srcenv.getMin().getX(),
            srcenv.getMin().getY(),
            srcenv.getMax().getX(),
            srcenv.getMax().getY(),
            0,
            0,
            srcwidth - 1,
            srcheight - 1);

    int minx = (int) Math.round(gt.getDestX(dstenv.getMin().getX()));
    int miny = (int) Math.round(gt.getDestY(dstenv.getMax().getY()));
    int maxx = (int) Math.round(gt.getDestX(dstenv.getMax().getX()));
    int maxy = (int) Math.round(gt.getDestY(dstenv.getMin().getY()));
    Rectangle rect = new Rectangle(minx, miny, maxx - minx + 1, maxy - miny + 1);
    LonLatEnvelope lonLatEnvelope = calcLonLatEnvelope(dstenv, getNativeSRSCode());

    return new Object[] {rect, dstenv, lonLatEnvelope};
  }
  private static boolean intersects(
      Envelope envelope, Code reqCRS, Envelope[] envs, LonLatEnvelope llEnv)
      throws UnknownCRSException {

    boolean res = false;
    String reqCRSCode = reqCRS.getCode();

    try {
      if (envs == null || envs.length == 0) {
        Envelope latlonEnv =
            GeometryFactory.createEnvelope(
                llEnv.getMin().getX(),
                llEnv.getMin().getY(),
                llEnv.getMax().getX(),
                llEnv.getMax().getY(),
                CRSFactory.create("EPSG:4326"));

        if (!"EPSG:4326".equals(reqCRSCode)) {
          res = intersects(envelope, reqCRSCode, latlonEnv, "EPSG:4326");
        } else {
          res = envelope.intersects(latlonEnv);
        }
      } else {
        for (int i = 0; i < envs.length && !res; i++) {
          if (intersects(
              envelope, reqCRSCode, envs[i], envs[i].getCoordinateSystem().getPrefixedName())) {
            res = true;
            break;
          }
        }
      }
    } catch (GeometryException ex) {
      LOG.logWarning("intersection test; translation into surface failed", ex);
    } catch (CRSException ex) {
      LOG.logWarning(
          "intersection test; transformation of reqeust envelope/valid area impossible", ex);
    } catch (CRSTransformationException ex) {
      LOG.logWarning("intersection test; transformation of reqeust envelope/valid area failed", ex);
    }
    return res;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.deegree.igeo.modules.remotecontrol.RequestHandler#perform(java.util.Map,
   * org.deegree.igeo.ApplicationContainer)
   */
  public String perform(Map<String, String> paramater, ApplicationContainer<?> appContainer)
      throws ModuleException {
    String tmp = paramater.get("OBJECTIDS");
    if (tmp == null || tmp.length() == 0) {
      throw new ModuleException(Messages.get("$DG10091"));
    }
    List<String> objIds = StringTools.toList(tmp, ",;", true);
    tmp = paramater.get("LAYER");
    if (tmp == null) {
      throw new ModuleException(Messages.get("$DG10092"));
    }

    MapModel mapModel = appContainer.getMapModel(null);
    LocalMapModelVisitor mv = new LocalMapModelVisitor(tmp);
    try {
      mapModel.walkLayerTree(mv);
    } catch (Exception e) {
      LOG.logError(e.getMessage(), e);
      throw new ModuleException(e.getMessage());
    }

    Layer layer = mv.getResult();
    if (layer == null) {
      throw new ModuleException(Messages.get("$DG10093", tmp));
    }
    layer.setVisible(true);

    // first select features in layer
    List<Identifier> ids = new ArrayList<Identifier>();
    for (String id : objIds) {
      ids.add(new Identifier(id));
    }
    SelectFeatureCommand cmd = new SelectFeatureCommand(layer, ids, false);
    try {
      appContainer.getCommandProcessor().executeSychronously(cmd, true);
    } catch (Exception e) {
      LOG.logError(e.getMessage(), e);
      throw new ModuleException(e.getMessage());
    }

    // get selected features as FeatureCollection and so their common bounding box
    FeatureCollection fc = layer.getSelectedFeatures();
    if (fc.size() == 0) {
      throw new ModuleException(Messages.get("$DG10094", paramater.get("OBJECTIDS")));
    }
    Envelope env = null;
    try {
      env = fc.getBoundedBy();
      if (env.getWidth() < 0.0001) {
        // feature collection just contains one point; set fix bbox width/height
        // 25 map units
        env = env.getBuffer(25);
      }
    } catch (GeometryException e) {
      LOG.logError(e.getMessage(), e);
      throw new ModuleException(e.getMessage());
    }

    // zoom to common bounding box of selected features
    ZoomCommand zcmd = new ZoomCommand(mapModel);
    zcmd.setZoomBox(
        env,
        mapModel.getTargetDevice().getPixelWidth(),
        mapModel.getTargetDevice().getPixelHeight());
    if ("TRUE".equalsIgnoreCase(paramater.get("sync"))) {
      try {
        appContainer.getCommandProcessor().executeSychronously(zcmd, true);
      } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        throw new ModuleException(e.getMessage());
      }
    } else {
      appContainer.getCommandProcessor().executeASychronously(zcmd);
    }

    return "feature selected";
  }
Ejemplo n.º 10
0
  /**
   * read part from ECW-file which falls within env and return this part as BufferedImage with
   * dimenions width and height
   *
   * @param env bounding box in world coordinates of requested part
   * @param width width of the returned image
   * @param height height of the returned image
   */
  public BufferedImage getBufferedImage(Envelope env, int width, int height) throws JNCSException {

    int bandlist[];
    int line, pRGBArray[] = null;

    // Setup the view parameters for the ecw file.
    bandlist = new int[ecwFile.numBands];
    for (int i = 0; i < ecwFile.numBands; i++) {
      bandlist[i] = i;
    }

    // Check if the envelope is within the area of the ecw-image
    double dWorldTLX = env.getMin().getX();
    double dWorldTLY = env.getMax().getY();

    LOG.logDebug("tlx: " + dWorldTLX + " tly: " + dWorldTLY);

    if (dWorldTLX < ecwFile.originX) dWorldTLX = ecwFile.originX;
    if (dWorldTLY > ecwFile.originY) dWorldTLY = ecwFile.originY;
    double dWorldBRX = env.getMax().getX();
    double dWorldBRY = env.getMin().getY();

    LOG.logDebug("brx: " + dWorldBRX + " bry: " + dWorldBRY);

    if (dWorldBRX > (ecwFile.originX + ((ecwFile.width - 1) * ecwFile.cellIncrementX))) // Huh?
      // ECW
      // does
      // not
      // except
      // the
      // full
      // width
      dWorldBRX = ecwFile.originX + ((ecwFile.width - 1) * ecwFile.cellIncrementX);
    if (dWorldBRY
        < (ecwFile.originY
            + (ecwFile.height * ecwFile.cellIncrementY)
            - (ecwFile.cellIncrementY / 2)))
      dWorldBRY =
          ecwFile.originY
              + (ecwFile.height * ecwFile.cellIncrementY)
              - (ecwFile.cellIncrementY / 2);

    // Work out the correct aspect for the setView call.
    // double dEnvAspect = (dWorldBRX - dWorldTLX) / (dWorldTLY - dWorldBRY);
    // double dImgAspect = (double) width / (double) height;

    LOG.logDebug("tlx: " + dWorldTLX + " tly: " + dWorldTLY);
    LOG.logDebug("brx: " + dWorldBRX + " bry: " + dWorldBRY);
    LOG.logDebug("width: " + width + " height: " + height);

    int nDatasetTLX = (int) Math.round((dWorldTLX - ecwFile.originX) / ecwFile.cellIncrementX);
    int nDatasetTLY = (int) Math.round((dWorldTLY - ecwFile.originY) / ecwFile.cellIncrementY);

    LOG.logDebug("ptlx: " + nDatasetTLX + " ptly: " + nDatasetTLY);

    int nDatasetBRX = (int) Math.round((dWorldBRX - ecwFile.originX) / ecwFile.cellIncrementX);
    int nDatasetBRY = (int) Math.round((dWorldBRY - ecwFile.originY) / ecwFile.cellIncrementY);

    LOG.logDebug("pbrx: " + nDatasetBRX + " pbry: " + nDatasetBRY);

    if (nDatasetBRX > (ecwFile.width - 1)) nDatasetBRX = ecwFile.width - 1;
    if (nDatasetBRY > (ecwFile.height - 1)) nDatasetBRY = ecwFile.height - 1;

    LOG.logDebug("pbrx: " + nDatasetBRX + " pbry: " + nDatasetBRY);

    // Check for supersampling
    int viewWidth = width;
    int viewHeight = height;
    if ((nDatasetBRX - nDatasetTLX) < viewWidth || (nDatasetBRY - nDatasetTLY) < viewHeight) {
      viewWidth = nDatasetBRX - nDatasetTLX;
      viewHeight = nDatasetBRY - nDatasetTLY;
    }
    if (viewWidth == 0) viewWidth = 1;
    if (viewHeight == 0) viewHeight = 1;

    LOG.logDebug("Width: " + width + " Height: " + height);
    LOG.logDebug("viewWidth: " + viewWidth + " viewHeight: " + viewHeight);

    // Create an image of the ecw file.
    BufferedImage ecwImage = new BufferedImage(viewWidth, viewHeight, BufferedImage.TYPE_INT_RGB);
    pRGBArray = new int[width];

    // Set the view
    ecwFile.setView(
        ecwFile.numBands,
        bandlist,
        nDatasetTLX,
        nDatasetTLY,
        nDatasetBRX,
        nDatasetBRY,
        viewWidth,
        viewHeight);

    // Read the scan lines
    for (line = 0; line < viewHeight; line++) {
      ecwFile.readLineRGBA(pRGBArray);
      ecwImage.setRGB(0, line, viewWidth, 1, pRGBArray, 0, viewWidth);
    }

    if (width != viewWidth || height != viewHeight) {
      LOG.logDebug("enlarge image");
      BufferedImage enlargedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics g = enlargedImg.getGraphics();
      g.drawImage(ecwImage, 0, 0, width, height, 0, 0, viewWidth, viewHeight, null);
      ecwImage = enlargedImg;
      g.dispose();
    }

    return ecwImage;
  }
  private static void transformRasterFile(
      String inFile,
      String inCRS,
      String outFile,
      String outCRS,
      Float imageQuality,
      int ppgridsize,
      int polynomOrder)
      throws Exception {

    System.out.println("Loading raster " + inFile);
    BufferedImage image = ImageUtils.loadImage(inFile);

    CoordinateSystem sourceCRS = CRSFactory.create(inCRS);
    CoordinateSystem targetCRS = CRSFactory.create(outCRS);

    WorldFile worldFile = WorldFile.readWorldFile(inFile, WorldFile.TYPE.CENTER, image);
    Envelope inEnvelope = worldFile.getEnvelope();

    // create minimal CoverageOffering for ImageGridCoverage
    // most parts are not used
    DomainSet ds = new DomainSet(new SpatialDomain(new Envelope[] {inEnvelope}));
    RangeSet rs = new RangeSet("", "");
    CodeList[] dummyCodeList = new CodeList[] {new CodeList("", new String[] {})};
    CodeList[] nativeSRSCodeList = new CodeList[] {new CodeList("", new String[] {inCRS})};

    SupportedSRSs supSRSs =
        new SupportedSRSs(dummyCodeList, dummyCodeList, dummyCodeList, nativeSRSCodeList);

    SupportedFormats supFormats = new SupportedFormats(dummyCodeList);

    CoverageOffering coverageOffering =
        new CoverageOffering("", "", "", null, null, null, ds, rs, supSRSs, supFormats, null, null);

    ImageGridCoverage igc = new ImageGridCoverage(coverageOffering, inEnvelope, image);

    GeoTransformer gt = new GeoTransformer(targetCRS);

    Envelope outEnvelope = gt.transform(inEnvelope, sourceCRS, true);

    // calculate new output size
    // use square pixels for output, ie. the aspect ratio changes
    double deltaX = outEnvelope.getWidth();
    double deltaY = outEnvelope.getHeight();
    double diagSize = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    // pixelSize for calculation of the new image size
    double pixelSize =
        diagSize / Math.sqrt(Math.pow(image.getWidth(), 2) + Math.pow(image.getHeight(), 2));
    int height = (int) (deltaY / pixelSize + 0.5);
    int width = (int) (deltaX / pixelSize + 0.5);
    // realPixelSize for center type world files, etc.
    double realPixelSize =
        diagSize
            / Math.sqrt(Math.pow(image.getWidth() - 1, 2) + Math.pow(image.getHeight() - 1, 2));

    System.out.println("Transforming raster from " + inCRS + " to " + outCRS);
    igc =
        (ImageGridCoverage)
            gt.transform(
                igc,
                outEnvelope,
                width,
                height,
                ppgridsize,
                polynomOrder,
                new InterpolationNearest());

    image = igc.getAsImage(-1, -1);

    System.out.println("Saving raster " + outFile);
    ImageUtils.saveImage(image, outFile, imageQuality);

    // save new WorldFile
    WorldFile outWorldFile = new WorldFile(realPixelSize, realPixelSize, 0.0f, 0.0f, outEnvelope);
    String basename = outFile.substring(0, outFile.lastIndexOf("."));
    WorldFile.writeWorldFile(outWorldFile, basename);
  }
Ejemplo n.º 12
0
    public void run() {
      Container container = getContentPane();
      container.removeAll();
      container.setLayout(new GridLayout(3, 1));

      int features = shapeFile.getRecordNum();
      container.add(new JLabel("Indexing..."));
      JProgressBar progressBar = new JProgressBar(1, features);
      progressBar.setStringPainted(true);
      container.add(progressBar);
      cancel = new JButton("Cancel");
      cancel.addActionListener(frame);
      container.add(cancel);
      pack();

      boolean geometry = false;
      DBaseIndex[] index = new DBaseIndex[properties.length];
      RTree rtree = null;

      try {
        String[] dataTypes = shapeFile.getDataTypes();
        int[] lengths = shapeFile.getDataLengths();

        if (geometryCheckBox.isSelected() && !hasGeometry) {
          geometry = true;
          rtree = new RTree(2, 11, fileName + ".rti");
        }

        boolean indexes = false;
        for (int i = 0; i < index.length; i++) {
          if (checkboxes[i].isSelected() && !hasIndex[i]) {
            index[i] =
                DBaseIndex.createIndex(
                    fileName + "$" + properties[i],
                    properties[i],
                    lengths[i],
                    uniqueBoxes[i].isSelected(),
                    (dataTypes[i].equalsIgnoreCase("N")
                        || dataTypes[i].equalsIgnoreCase("I")
                        || dataTypes[i].equalsIgnoreCase("F")));
            indexes = true;
          } else index[i] = null;
        }

        if (geometry || indexes) {
          for (int i = 1; i < features + 1; i++) {
            Feature feature = shapeFile.getFeatureByRecNo(i);

            if (geometry) {
              Geometry[] geometries = feature.getGeometryPropertyValues();
              if (geometries.length == 0) {
                LOG.logInfo("no geometries at recno" + i);
                continue;
              }
              Envelope envelope = null;
              // TODO: deal with more than one geometry; handle geometry=null (allowed
              // in shapefile)
              envelope = (feature.getDefaultGeometryPropertyValue()).getEnvelope();
              if (envelope == null) { // assume a Point-geometry
                Point pnt = (Point) geometries[0];
                envelope =
                    GeometryFactory.createEnvelope(
                        pnt.getX(), pnt.getY(), pnt.getX(), pnt.getY(), null);
              }
              HyperBoundingBox box =
                  new HyperBoundingBox(
                      new HyperPoint(envelope.getMin().getAsArray()),
                      new HyperPoint(envelope.getMax().getAsArray()));
              rtree.insert(new Integer(i), box);
            }

            for (int j = 0; j < index.length; j++) {
              if (index[j] != null) {
                QualifiedName qn = new QualifiedName(properties[j]);
                index[j].addKey((Comparable) feature.getDefaultProperty(qn), i);
              }
            }

            progressBar.setValue(i);

            synchronized (this) {
              if (stop) {
                shapeFile.close();
                if (geometry) {
                  rtree.close();
                  new File(fileName + ".rti").delete();
                }
                for (int j = 0; j < index.length; j++) {
                  if (index[j] != null) {
                    index[j].close();
                    new File(fileName + "$" + properties[j] + ".ndx").delete();
                  }
                }
                System.exit(3);
              }
            }
          }
        }

        try {
          if (geometry) {
            rtree.close();
          }
          shapeFile.close();

          for (int i = 0; i < index.length; i++) if (index[i] != null) index[i].close();
        } catch (Exception e) {
          e.printStackTrace();
          JOptionPane.showMessageDialog(frame, e);
          System.exit(1);
        }

        if (!geometryCheckBox.isSelected() && hasGeometry) {
          new File(fileName + ".rti").delete();
        }

        for (int i = 0; i < index.length; i++) {
          if (!checkboxes[i].isSelected() && hasIndex[i]) {
            new File(fileName + "$" + properties[i] + ".ndx").delete();
          }
        }

        System.exit(0);
      } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(frame, ex);
        System.exit(1);
      }
    }