Changeset 23187 in osm for applications/editors/josm
- Timestamp:
- 2010-09-15T18:50:23+02:00 (15 years ago)
- Location:
- applications/editors/josm/plugins/ImportImagePlugin
- Files:
-
- 6 edited
-
build.xml (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageImportPlugin.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageLayer.java (modified) (3 diffs)
-
src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/ImportImagePlugin/LoadImageAction.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
applications/editors/josm/plugins/ImportImagePlugin/build.xml
r23145 r23187 121 121 <attribute name="Plugin-Date" value="${version.entry.commit.date}"/> 122 122 <attribute name="Plugin-Description" value="Plugin for importing spatial referenced images"/> 123 <attribute name="Plugin-Link" value=" -- will soon be added -- "/> 124 <attribute name="Plugin-Mainversion" value="1.0"/> 123 <attribute name="Plugin-Mainversion" value="3376"/> 125 124 <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/> 126 125 <attribute name="Class-Path" value="."/> -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageImportPlugin.java
r23145 r23187 31 31 */ 32 32 public class ImageImportPlugin extends Plugin{ 33 34 private static Logger logger;35 36 JMenu mainmenu = null;37 JosmAction loadFileAction = null;38 39 // custom Classloader40 static ClassLoader pluginClassLoader;41 42 // plugin proerties43 static Properties pluginProps;44 45 // path constants46 static final String PLUGIN_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/";47 static final String PLUGINPROPERTIES_PATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/pluginProperties.properties";48 static final String PLUGINLIBRARIES_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/lib/";49 static final String PLUGINPROPERTIES_FILENAME = "pluginProperties.properties";50 static final String LOGGING_PROPERTIES_FILEPATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/log4j.properties/";51 52 53 public Properties getPluginProps() {54 return pluginProps;55 }56 57 58 /**59 * constructor60 *61 * @param info62 */63 public ImageImportPlugin(PluginInformation info){64 super(info);65 66 try {67 68 // First create custom ClassLoader to load resources from the main JAR69 pluginClassLoader = createPluginClassLoader();70 71 // Initialize logger72 initializeLogger(pluginClassLoader);73 74 // Check whether plugin has already been installed. Otherwise install75 checkInstallation();76 77 // If resources are available load properties from plugin directory78 if(pluginProps == null || pluginProps.isEmpty())79 {80 pluginProps = new Properties();81 pluginProps.load(new File(PLUGINPROPERTIES_PATH).toURI().toURL().openStream());82 logger.debug("Plugin properties loaded");83 }84 85 /* Change class path:86 * Use java reflection methods to add URLs to the class-path.87 * Changes take effect when calling methods of other plugin classes88 * (new threads)89 * */90 URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();91 String[] libraryNames = pluginProps.getProperty("libraries").split(",");92 Class<URLClassLoader> sysclass = URLClassLoader.class;93 Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});94 method.setAccessible(true);95 for (int i = 0; i < libraryNames.length; i++) {96 File library = new File(PLUGINLIBRARIES_DIR + "/" + libraryNames[i]);97 method.invoke(sysLoader, new Object[]{library.toURI().toURL()});98 }99 100 101 // load information about supported reference systems102 PluginOperations.loadCRSData(pluginProps);103 104 // create new Action for menu entry105 LoadImageAction loadFileAction = new LoadImageAction();106 loadFileAction.setEnabled(true);107 108 // add menu entries109 Main.main.menu.fileMenu.insert(loadFileAction, 8);110 Main.main.menu.fileMenu.insertSeparator(9);111 112 113 } catch (Exception e) {114 logger.fatal("Error while loading plugin", e);115 try {116 throw e;117 } catch (Exception e1) {118 e1.printStackTrace();119 }120 }121 122 logger.info("Plugin successfully loaded.");123 124 }125 126 127 128 /**129 * Checks whether plugin resources are available.130 * If not, start install procedure.131 *132 * @throws IOException133 */134 private void checkInstallation() throws IOException135 {136 137 // check plugin resource state138 boolean isInstalled = true;139 if(!new File(PLUGINPROPERTIES_PATH).exists()140 || !new File(PLUGIN_DIR).exists()141 || !new File(PLUGINLIBRARIES_DIR).exists())142 isInstalled = false;143 144 145 // if properties file doesn't exist, install plugin146 if(!isInstalled)147 {148 149 /*----------- Begin installation ---------------*/150 151 // check if plugin directory exist152 File pluginDir = new File(PLUGIN_DIR);153 if(!pluginDir.exists()){154 pluginDir.mkdir();155 }156 157 // check if "lib" directory exist158 File libDir = new File(PLUGINLIBRARIES_DIR);159 if(!libDir.exists()){160 libDir.mkdir();161 }162 163 // create local properties file164 if(pluginProps == null || pluginProps.isEmpty()){165 166 FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH));167 URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME);168 pluginProps = new Properties();169 pluginProps.load(propertiesURL.openStream());170 pluginProps.store(fw, null);171 fw.close();172 logger.debug("Plugin properties loaded");173 }174 175 if(!new File(LOGGING_PROPERTIES_FILEPATH).exists())176 {177 FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH));178 URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties");179 Properties loggingProps = new Properties();180 loggingProps.load(propertiesURL.openStream());181 loggingProps.store(fw, null);182 fw.close();183 logger.debug("Logging properties created");184 }185 186 187 // Copy all needed JAR files to $PLUGIN_DIR$/lib/188 String[] libStrings = pluginProps.getProperty("libraries").split(",");189 190 for (int i = 0; i < libStrings.length; i++) {191 192 URL url = pluginClassLoader.getResource("lib/" + libStrings[i]);193 194 FileOutputStream out = null;195 196 try{197 out = new FileOutputStream(new File(libDir, libStrings[i]));198 } catch (FileNotFoundException e) {199 break;200 }201 202 BufferedInputStream in = null;203 try204 {205 in = new BufferedInputStream(url.openStream());206 207 byte[] buffer = new byte[1024];208 while (true)209 {210 int count = in.read(buffer);211 if (count == -1)212 break;213 out.write(buffer, 0, count);214 }215 }216 finally217 {218 if (in != null)219 in.close();220 }221 }222 logger.debug("Plugin successfully installed");223 }224 }225 226 227 /**228 * Initialize logger using plugin classloader.229 *230 * @param cl231 */232 private void initializeLogger(ClassLoader cl) {233 234 Properties props = new Properties();235 try {236 props.load(new File(LOGGING_PROPERTIES_FILEPATH).toURI().toURL().openStream());237 238 // Set file for logging here:239 props.setProperty("log4j.appender.MyRoFiAppender.file",240 (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log"));241 242 PropertyConfigurator.configure(props);243 244 logger = Logger.getLogger(ImageImportPlugin.class);245 246 logger.info("Logger successfully initialized.");247 248 return;249 250 } catch (IOException e) {251 System.out.println("Logging properties file not found. Using standard settings.");252 }253 254 // if no log4j.properties file can be found, initialize manually:255 256 props.setProperty("log4j.rootLogger", "INFO, A");257 props.setProperty("log4j.appender.A", "org.apache.log4j.FileAppender");258 259 props.setProperty("log4j.appender.A.layout",260 "org.apache.log4j.PatternLayout ");261 props.setProperty("log4j.appender.A.layout.ConversionPattern",262 "%d{ISO8601} %-5p [%t] %c: %m%n");263 264 // Set file for logging here:265 props.setProperty("log4j.appender.A.file",266 (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log"));267 268 PropertyConfigurator.configure(props);269 logger = Logger.getLogger(ImageImportPlugin.class);270 logger.info("Logger successfully initialized with standard settings.");271 272 }273 274 /**275 * get a plugin-specific classloader.276 *277 * @return278 * @throws MalformedURLException279 */280 private ClassLoader createPluginClassLoader() throws MalformedURLException281 {282 ClassLoader loader = null;283 loader = URLClassLoader.newInstance(284 new URL[] { new File(Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImportImagePlugin.jar").toURI().toURL()},285 ImageImportPlugin.class.getClassLoader()286 );287 288 return loader;289 }290 33 34 private static Logger logger; 35 36 JMenu mainmenu = null; 37 JosmAction loadFileAction = null; 38 39 // custom Classloader 40 static ClassLoader pluginClassLoader; 41 42 // plugin proerties 43 static Properties pluginProps; 44 45 // path constants 46 static final String PLUGIN_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/"; 47 static final String PLUGINPROPERTIES_PATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/pluginProperties.properties"; 48 static final String PLUGINLIBRARIES_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/lib/"; 49 static final String PLUGINPROPERTIES_FILENAME = "pluginProperties.properties"; 50 static final String LOGGING_PROPERTIES_FILEPATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/log4j.properties/"; 51 52 53 public Properties getPluginProps() { 54 return pluginProps; 55 } 56 57 58 /** 59 * constructor 60 * 61 * @param info 62 */ 63 public ImageImportPlugin(PluginInformation info){ 64 super(info); 65 66 try { 67 68 // First create custom ClassLoader to load resources from the main JAR 69 pluginClassLoader = createPluginClassLoader(); 70 71 // Initialize logger 72 initializeLogger(pluginClassLoader); 73 74 // Check whether plugin has already been installed. Otherwise install 75 checkInstallation(); 76 77 // If resources are available load properties from plugin directory 78 if(pluginProps == null || pluginProps.isEmpty()) 79 { 80 pluginProps = new Properties(); 81 pluginProps.load(new File(PLUGINPROPERTIES_PATH).toURI().toURL().openStream()); 82 logger.debug("Plugin properties loaded"); 83 } 84 85 /* Change class path: 86 * Use java reflection methods to add URLs to the class-path. 87 * Changes take effect when calling methods of other plugin classes 88 * (new threads) 89 * */ 90 URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); 91 String[] libraryNames = pluginProps.getProperty("libraries").split(","); 92 Class<URLClassLoader> sysclass = URLClassLoader.class; 93 Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class}); 94 method.setAccessible(true); 95 for (int i = 0; i < libraryNames.length; i++) { 96 File library = new File(PLUGINLIBRARIES_DIR + "/" + libraryNames[i]); 97 method.invoke(sysLoader, new Object[]{library.toURI().toURL()}); 98 } 99 100 101 // load information about supported reference systems 102 PluginOperations.loadCRSData(pluginProps); 103 104 // create new Action for menu entry 105 LoadImageAction loadFileAction = new LoadImageAction(); 106 loadFileAction.setEnabled(true); 107 108 // add menu entries 109 Main.main.menu.fileMenu.insert(loadFileAction, 8); 110 Main.main.menu.fileMenu.insertSeparator(9); 111 112 113 } catch (Exception e) { 114 logger.fatal("Error while loading plugin", e); 115 try { 116 throw e; 117 } catch (Exception e1) { 118 e1.printStackTrace(); 119 } 120 } 121 122 logger.info("Plugin successfully loaded."); 123 124 } 125 126 127 128 /** 129 * Checks whether plugin resources are available. 130 * If not, start install procedure. 131 * 132 * @throws IOException 133 */ 134 private void checkInstallation() throws IOException 135 { 136 137 // check plugin resource state 138 boolean isInstalled = true; 139 if(!new File(PLUGINPROPERTIES_PATH).exists() 140 || !new File(PLUGIN_DIR).exists() 141 || !new File(PLUGINLIBRARIES_DIR).exists()) 142 isInstalled = false; 143 144 145 // if properties file doesn't exist, install plugin 146 if(!isInstalled) 147 { 148 149 /*----------- Begin installation ---------------*/ 150 151 // check if plugin directory exist 152 File pluginDir = new File(PLUGIN_DIR); 153 if(!pluginDir.exists()){ 154 pluginDir.mkdir(); 155 } 156 157 // check if "lib" directory exist 158 File libDir = new File(PLUGINLIBRARIES_DIR); 159 if(!libDir.exists()){ 160 libDir.mkdir(); 161 } 162 163 // create local properties file 164 if(pluginProps == null || pluginProps.isEmpty()){ 165 166 FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH)); 167 URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME); 168 pluginProps = new Properties(); 169 pluginProps.load(propertiesURL.openStream()); 170 pluginProps.store(fw, null); 171 fw.close(); 172 logger.debug("Plugin properties loaded"); 173 } 174 175 if(!new File(LOGGING_PROPERTIES_FILEPATH).exists()) 176 { 177 FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH)); 178 URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties"); 179 Properties loggingProps = new Properties(); 180 loggingProps.load(propertiesURL.openStream()); 181 loggingProps.store(fw, null); 182 fw.close(); 183 logger.debug("Logging properties created"); 184 } 185 186 187 // Copy all needed JAR files to $PLUGIN_DIR$/lib/ 188 String[] libStrings = pluginProps.getProperty("libraries").split(","); 189 190 for (int i = 0; i < libStrings.length; i++) { 191 192 URL url = pluginClassLoader.getResource("lib/" + libStrings[i]); 193 194 FileOutputStream out = null; 195 196 try{ 197 out = new FileOutputStream(new File(libDir, libStrings[i])); 198 } catch (FileNotFoundException e) { 199 break; 200 } 201 202 BufferedInputStream in = null; 203 try 204 { 205 in = new BufferedInputStream(url.openStream()); 206 207 byte[] buffer = new byte[1024]; 208 while (true) 209 { 210 int count = in.read(buffer); 211 if (count == -1) 212 break; 213 out.write(buffer, 0, count); 214 } 215 } 216 finally 217 { 218 if (in != null) 219 in.close(); 220 } 221 } 222 logger.debug("Plugin successfully installed"); 223 } 224 } 225 226 227 /** 228 * Initialize logger using plugin classloader. 229 * 230 * @param cl 231 */ 232 private void initializeLogger(ClassLoader cl) { 233 234 Properties props = new Properties(); 235 try { 236 props.load(new File(LOGGING_PROPERTIES_FILEPATH).toURI().toURL().openStream()); 237 238 // Set file for logging here: 239 props.setProperty("log4j.appender.MyRoFiAppender.file", 240 (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log")); 241 242 PropertyConfigurator.configure(props); 243 244 logger = Logger.getLogger(ImageImportPlugin.class); 245 246 logger.info("Logger successfully initialized."); 247 248 return; 249 250 } catch (IOException e) { 251 System.out.println("Logging properties file not found. Using standard settings."); 252 } 253 254 // if no log4j.properties file can be found, initialize manually: 255 256 props.setProperty("log4j.rootLogger", "INFO, A"); 257 props.setProperty("log4j.appender.A", "org.apache.log4j.FileAppender"); 258 259 props.setProperty("log4j.appender.A.layout", 260 "org.apache.log4j.PatternLayout "); 261 props.setProperty("log4j.appender.A.layout.ConversionPattern", 262 "%d{ISO8601} %-5p [%t] %c: %m%n"); 263 264 // Set file for logging here: 265 props.setProperty("log4j.appender.A.file", 266 (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log")); 267 268 PropertyConfigurator.configure(props); 269 logger = Logger.getLogger(ImageImportPlugin.class); 270 logger.info("Logger successfully initialized with standard settings."); 271 272 } 273 274 /** 275 * get a plugin-specific classloader. 276 * 277 * @return 278 * @throws MalformedURLException 279 */ 280 private ClassLoader createPluginClassLoader() throws MalformedURLException 281 { 282 ClassLoader loader = null; 283 loader = URLClassLoader.newInstance( 284 new URL[] { new File(Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImportImagePlugin.jar").toURI().toURL()}, 285 ImageImportPlugin.class.getClassLoader() 286 ); 287 288 return loader; 289 } 290 291 291 } -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageLayer.java
r23145 r23187 12 12 13 13 import javax.media.jai.PlanarImage; 14 import javax.swing.Action; 14 15 import javax.swing.AbstractAction; 15 16 import javax.swing.Icon; … … 40 41 41 42 /** 42 * Layer which contains spatial referenced image data.43 * Layer which contains spatial referenced image data. 43 44 * 44 45 * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny … … 47 48 public class ImageLayer extends Layer { 48 49 49 private Logger logger = Logger.getLogger(ImageLayer.class);50 51 private File imageFile;52 53 private BufferedImage image = null;54 55 // coordinates of upper left corner56 private EastNorth upperLeft;57 // Angle of rotation of the image58 private double angle = 0.0;59 60 // current bbox61 private Envelope2D bbox;62 63 // Layer icon64 private Icon layericon = null;65 66 // reference system of the oringinal image67 private CoordinateReferenceSystem sourceRefSys;68 69 70 71 /**72 * Constructor73 *74 * @param file75 * @throws IOException76 */77 public ImageLayer(File file) throws IOException {78 super(file.getName());79 80 this.imageFile = file;81 this.image = (BufferedImage) createImage();82 layericon = new ImageIcon(ImageImportPlugin.pluginClassLoader.getResource("images/layericon.png"));83 84 }85 86 /**87 * create spatial referenced image.88 *89 * @return90 * @throws IOException91 */92 private Image createImage() throws IOException {93 94 // geotools type for images and value coverages95 GridCoverage2D coverage = null;96 try {97 // create a grid coverage from the image98 coverage = PluginOperations.createGridFromFile(imageFile, null);99 this.sourceRefSys = coverage.getCoordinateReferenceSystem();100 101 // now reproject grid coverage102 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));103 104 } catch (FactoryException e) {105 logger.error("Error while creating GridCoverage:",e);106 throw new IOException(e.getMessage());107 } catch (Exception e) {108 if(e.getMessage().contains("No projection file found"))109 {110 int useDefaultCRS = JOptionPane.showConfirmDialog(Main.parent, "<html>No projection file (.prj) found.<br>Use the default Coordinate Reference System instead?</html>", "Missing projection", JOptionPane.YES_NO_OPTION);111 if (useDefaultCRS == 0)112 {113 try {114 // create a grid coverage from the image115 coverage = PluginOperations.createGridFromFile(imageFile, PluginOperations.defaultSourceCRS);116 this.sourceRefSys = coverage.getCoordinateReferenceSystem();117 118 // now reproject grid coverage119 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));120 } catch (Exception e1) {121 logger.error("Error while creating GridCoverage:",e1);122 throw new IOException(e1);123 }124 }125 else{126 logger.debug("Layer creation cancled by user due to missing projection information.");127 throw new LayerCreationCancledException();128 }129 130 }131 else132 {133 logger.error("Error while creating GridCoverage:",e);134 throw new IOException(e);135 }136 137 }138 logger.debug("Coverage created: " + coverage);139 140 // TODO141 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage142 .getEnvelope2D().x143 + coverage.getEnvelope2D().width);144 angle = 0;145 bbox = coverage.getEnvelope2D();146 147 // Refresh148 // Main.map.mapView.repaint();149 // PlanarImage image = (PlanarImage) coverage.getRenderedImage();150 // logger.info("Color Model: " + coverage.getRenderedImage().getColorModel());151 ImageWorker worker = new ImageWorker(coverage.getRenderedImage());152 153 return worker.getBufferedImage();154 }155 156 @Override157 public void paint(Graphics2D g2, MapView mv, Bounds bounds) {158 159 if (image != null && g2 != null) {160 161 // Position image at the right graphical place162 EastNorth center = Main.map.mapView.getCenter();163 EastNorth leftop = Main.map.mapView.getEastNorth(0, 0);164 double pixel_per_lon_degree = (Main.map.mapView.getWidth() / 2.0)165 / (center.east() - leftop.east());166 double pixel_per_lat_degree = (Main.map.mapView.getHeight() / 2.0)167 / (leftop.north() - center.north());168 169 // This is now the offset in screen pixels170 double pic_offset_x = ((upperLeft.east() - leftop.east()) * pixel_per_lon_degree);171 double pic_offset_y = ((leftop.north() - upperLeft.north()) * pixel_per_lat_degree);172 173 Graphics2D g = (Graphics2D) g2.create();174 175 // Move picture by offset from upper left corner176 g.translate(pic_offset_x, pic_offset_y);177 178 // Rotate image by angle179 g.rotate(angle * Math.PI / 180.0);180 181 // Determine scale to fit JOSM extents182 ProjectionBounds projbounds = Main.map.mapView183 .getProjectionBounds();184 185 double width = projbounds.max.getX() - projbounds.min.getX();186 double height = projbounds.max.getY() - projbounds.min.getY();187 188 double ratio_x = (this.bbox.getMaxY() - this.bbox.getMinY())189 / width;190 double ratio_y = (this.bbox.getMaxX() - this.bbox.getMinX())191 / height;192 193 double pixels4bbox_width = ratio_x * Main.map.mapView.getWidth();194 double pixels4bbox_height = ratio_y * Main.map.mapView.getHeight();195 196 // Scale image to JOSM extents197 double scalex = pixels4bbox_width / image.getWidth();198 double scaley = pixels4bbox_height / image.getHeight();199 200 g.scale(scalex, scaley);201 202 // Draw picture203 g.drawImage(image, 0, 0, null);204 205 } else {206 logger.error("Error while dawing image: image == null or Graphics == null");207 }208 }209 210 public Envelope2D getBbox() {211 return bbox;212 }213 214 @Override215 public Icon getIcon() {216 // TODO Auto-generated method stub217 return this.layericon;218 }219 220 @Override221 public Object getInfoComponent() {222 // TODO Auto-generated method stub223 return null;224 }225 226 @Override227 publicComponent[] getMenuEntries() {228 return new Component[]{229 new JMenuItem(LayerListDialog.getInstance().createActivateLayerAction(this)),230 new JMenuItem(LayerListDialog.getInstance().createShowHideLayerAction(this)),231 new JMenuItem(LayerListDialog.getInstance().createDeleteLayerAction(this)),232 new JSeparator(),233 new JMenuItem(newRenameLayerAction(getAssociatedFile(), this)),234 new JMenuItem(newLayerPropertiesAction(this)),235 new JSeparator(),236 new JMenuItem(newLayerListPopup.InfoAction(this))};237 }238 239 @Override240 public boolean isMergable(Layer arg0) {241 // TODO Auto-generated method stub242 return false;243 }244 245 @Override246 public void mergeFrom(Layer arg0) {247 // TODO Auto-generated method stub248 249 }250 251 @Override252 public void visitBoundingBox(BoundingXYVisitor arg0) {253 // TODO Auto-generated method stub254 }255 256 257 @Override258 public String getToolTipText() {259 // TODO Auto-generated method stub260 return this.getName();261 }262 263 264 public File getImageFile() {265 return imageFile;266 }267 268 public BufferedImage getImage() {269 return image;270 }271 272 /**273 * loads the image and reprojects it using a transformation274 * calculated by the new reference system.275 *276 * @param newRefSys277 * @throws IOException278 * @throws FactoryException279 * @throws NoSuchAuthorityCodeException280 */281 void resample(CoordinateReferenceSystem refSys) throws IOException, NoSuchAuthorityCodeException, FactoryException282 {283 284 GridCoverage2D coverage = PluginOperations.createGridFromFile(this.imageFile, refSys);285 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));286 this.bbox = coverage.getEnvelope2D();287 this.image = ((PlanarImage)coverage.getRenderedImage()).getAsBufferedImage();288 289 // TODO290 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage291 .getEnvelope2D().x292 + coverage.getEnvelope2D().width);293 angle = 0;294 295 // repaint and zoom to new bbox296 Main.map.mapView.repaint();297 LatLon min = new LatLon(bbox.getMinX(), bbox.getMinY());298 LatLon max = new LatLon(bbox.getMaxX(), bbox.getMaxY());299 Main.map.mapView.zoomTo(new Bounds(min, max));300 301 302 }303 304 /**305 * Action that creates a dialog GUI element with properties of a layer.306 *307 */308 public class LayerPropertiesAction extends AbstractAction309 {310 public ImageLayer imageLayer;311 312 public LayerPropertiesAction(ImageLayer imageLayer){313 super(tr("Layer Properties"));314 this.imageLayer = imageLayer;315 }316 317 public void actionPerformed(ActionEvent arg0) {318 319 LayerPropertiesDialog layerProps = new LayerPropertiesDialog(imageLayer, PluginOperations.crsDescriptions);320 layerProps.setLocation(Main.parent.getWidth() / 4 , Main.parent.getHeight() / 4);321 layerProps.setVisible(true);322 }323 324 }325 326 /**327 * Exception which represents that the layer creation has been cancled by the328 * user.329 *330 */331 class LayerCreationCancledException extends IOException{332 }333 334 335 336 public CoordinateReferenceSystem getSourceRefSys() {337 return sourceRefSys;338 }339 340 public void setSourceRefSys(CoordinateReferenceSystem sourceRefSys) {341 this.sourceRefSys = sourceRefSys;342 }50 private Logger logger = Logger.getLogger(ImageLayer.class); 51 52 private File imageFile; 53 54 private BufferedImage image = null; 55 56 // coordinates of upper left corner 57 private EastNorth upperLeft; 58 // Angle of rotation of the image 59 private double angle = 0.0; 60 61 // current bbox 62 private Envelope2D bbox; 63 64 // Layer icon 65 private Icon layericon = null; 66 67 // reference system of the oringinal image 68 private CoordinateReferenceSystem sourceRefSys; 69 70 71 72 /** 73 * Constructor 74 * 75 * @param file 76 * @throws IOException 77 */ 78 public ImageLayer(File file) throws IOException { 79 super(file.getName()); 80 81 this.imageFile = file; 82 this.image = (BufferedImage) createImage(); 83 layericon = new ImageIcon(ImageImportPlugin.pluginClassLoader.getResource("images/layericon.png")); 84 85 } 86 87 /** 88 * create spatial referenced image. 89 * 90 * @return 91 * @throws IOException 92 */ 93 private Image createImage() throws IOException { 94 95 // geotools type for images and value coverages 96 GridCoverage2D coverage = null; 97 try { 98 // create a grid coverage from the image 99 coverage = PluginOperations.createGridFromFile(imageFile, null); 100 this.sourceRefSys = coverage.getCoordinateReferenceSystem(); 101 102 // now reproject grid coverage 103 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode())); 104 105 } catch (FactoryException e) { 106 logger.error("Error while creating GridCoverage:",e); 107 throw new IOException(e.getMessage()); 108 } catch (Exception e) { 109 if(e.getMessage().contains("No projection file found")) 110 { 111 int useDefaultCRS = JOptionPane.showConfirmDialog(Main.parent, "<html>No projection file (.prj) found.<br>Use the default Coordinate Reference System instead?</html>", "Missing projection", JOptionPane.YES_NO_OPTION); 112 if (useDefaultCRS == 0) 113 { 114 try { 115 // create a grid coverage from the image 116 coverage = PluginOperations.createGridFromFile(imageFile, PluginOperations.defaultSourceCRS); 117 this.sourceRefSys = coverage.getCoordinateReferenceSystem(); 118 119 // now reproject grid coverage 120 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode())); 121 } catch (Exception e1) { 122 logger.error("Error while creating GridCoverage:",e1); 123 throw new IOException(e1); 124 } 125 } 126 else{ 127 logger.debug("Layer creation cancled by user due to missing projection information."); 128 throw new LayerCreationCancledException(); 129 } 130 131 } 132 else 133 { 134 logger.error("Error while creating GridCoverage:",e); 135 throw new IOException(e); 136 } 137 138 } 139 logger.debug("Coverage created: " + coverage); 140 141 // TODO 142 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage 143 .getEnvelope2D().x 144 + coverage.getEnvelope2D().width); 145 angle = 0; 146 bbox = coverage.getEnvelope2D(); 147 148 // Refresh 149 // Main.map.mapView.repaint(); 150 // PlanarImage image = (PlanarImage) coverage.getRenderedImage(); 151 // logger.info("Color Model: " + coverage.getRenderedImage().getColorModel()); 152 ImageWorker worker = new ImageWorker(coverage.getRenderedImage()); 153 154 return worker.getBufferedImage(); 155 } 156 157 @Override 158 public void paint(Graphics2D g2, MapView mv, Bounds bounds) { 159 160 if (image != null && g2 != null) { 161 162 // Position image at the right graphical place 163 EastNorth center = Main.map.mapView.getCenter(); 164 EastNorth leftop = Main.map.mapView.getEastNorth(0, 0); 165 double pixel_per_lon_degree = (Main.map.mapView.getWidth() / 2.0) 166 / (center.east() - leftop.east()); 167 double pixel_per_lat_degree = (Main.map.mapView.getHeight() / 2.0) 168 / (leftop.north() - center.north()); 169 170 // This is now the offset in screen pixels 171 double pic_offset_x = ((upperLeft.east() - leftop.east()) * pixel_per_lon_degree); 172 double pic_offset_y = ((leftop.north() - upperLeft.north()) * pixel_per_lat_degree); 173 174 Graphics2D g = (Graphics2D) g2.create(); 175 176 // Move picture by offset from upper left corner 177 g.translate(pic_offset_x, pic_offset_y); 178 179 // Rotate image by angle 180 g.rotate(angle * Math.PI / 180.0); 181 182 // Determine scale to fit JOSM extents 183 ProjectionBounds projbounds = Main.map.mapView 184 .getProjectionBounds(); 185 186 double width = projbounds.max.getX() - projbounds.min.getX(); 187 double height = projbounds.max.getY() - projbounds.min.getY(); 188 189 double ratio_x = (this.bbox.getMaxY() - this.bbox.getMinY()) 190 / width; 191 double ratio_y = (this.bbox.getMaxX() - this.bbox.getMinX()) 192 / height; 193 194 double pixels4bbox_width = ratio_x * Main.map.mapView.getWidth(); 195 double pixels4bbox_height = ratio_y * Main.map.mapView.getHeight(); 196 197 // Scale image to JOSM extents 198 double scalex = pixels4bbox_width / image.getWidth(); 199 double scaley = pixels4bbox_height / image.getHeight(); 200 201 g.scale(scalex, scaley); 202 203 // Draw picture 204 g.drawImage(image, 0, 0, null); 205 206 } else { 207 logger.error("Error while dawing image: image == null or Graphics == null"); 208 } 209 } 210 211 public Envelope2D getBbox() { 212 return bbox; 213 } 214 215 @Override 216 public Icon getIcon() { 217 // TODO Auto-generated method stub 218 return this.layericon; 219 } 220 221 @Override 222 public Object getInfoComponent() { 223 // TODO Auto-generated method stub 224 return null; 225 } 226 227 @Override 228 public Action[] getMenuEntries() { 229 return new Action[]{ 230 LayerListDialog.getInstance().createActivateLayerAction(this), 231 LayerListDialog.getInstance().createShowHideLayerAction(), 232 LayerListDialog.getInstance().createDeleteLayerAction(), 233 SeparatorLayerAction.INSTANCE, 234 new RenameLayerAction(getAssociatedFile(), this), 235 new LayerPropertiesAction(this), 236 SeparatorLayerAction.INSTANCE, 237 new LayerListPopup.InfoAction(this)}; 238 } 239 240 @Override 241 public boolean isMergable(Layer arg0) { 242 // TODO Auto-generated method stub 243 return false; 244 } 245 246 @Override 247 public void mergeFrom(Layer arg0) { 248 // TODO Auto-generated method stub 249 250 } 251 252 @Override 253 public void visitBoundingBox(BoundingXYVisitor arg0) { 254 // TODO Auto-generated method stub 255 } 256 257 258 @Override 259 public String getToolTipText() { 260 // TODO Auto-generated method stub 261 return this.getName(); 262 } 263 264 265 public File getImageFile() { 266 return imageFile; 267 } 268 269 public BufferedImage getImage() { 270 return image; 271 } 272 273 /** 274 * loads the image and reprojects it using a transformation 275 * calculated by the new reference system. 276 * 277 * @param newRefSys 278 * @throws IOException 279 * @throws FactoryException 280 * @throws NoSuchAuthorityCodeException 281 */ 282 void resample(CoordinateReferenceSystem refSys) throws IOException, NoSuchAuthorityCodeException, FactoryException 283 { 284 285 GridCoverage2D coverage = PluginOperations.createGridFromFile(this.imageFile, refSys); 286 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode())); 287 this.bbox = coverage.getEnvelope2D(); 288 this.image = ((PlanarImage)coverage.getRenderedImage()).getAsBufferedImage(); 289 290 // TODO 291 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage 292 .getEnvelope2D().x 293 + coverage.getEnvelope2D().width); 294 angle = 0; 295 296 // repaint and zoom to new bbox 297 Main.map.mapView.repaint(); 298 LatLon min = new LatLon(bbox.getMinX(), bbox.getMinY()); 299 LatLon max = new LatLon(bbox.getMaxX(), bbox.getMaxY()); 300 Main.map.mapView.zoomTo(new Bounds(min, max)); 301 302 303 } 304 305 /** 306 * Action that creates a dialog GUI element with properties of a layer. 307 * 308 */ 309 public class LayerPropertiesAction extends AbstractAction 310 { 311 public ImageLayer imageLayer; 312 313 public LayerPropertiesAction(ImageLayer imageLayer){ 314 super(tr("Layer Properties")); 315 this.imageLayer = imageLayer; 316 } 317 318 public void actionPerformed(ActionEvent arg0) { 319 320 LayerPropertiesDialog layerProps = new LayerPropertiesDialog(imageLayer, PluginOperations.crsDescriptions); 321 layerProps.setLocation(Main.parent.getWidth() / 4 , Main.parent.getHeight() / 4); 322 layerProps.setVisible(true); 323 } 324 325 } 326 327 /** 328 * Exception which represents that the layer creation has been cancled by the 329 * user. 330 * 331 */ 332 class LayerCreationCancledException extends IOException{ 333 } 334 335 336 337 public CoordinateReferenceSystem getSourceRefSys() { 338 return sourceRefSys; 339 } 340 341 public void setSourceRefSys(CoordinateReferenceSystem sourceRefSys) { 342 this.sourceRefSys = sourceRefSys; 343 } 343 344 } -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java
r23145 r23187 42 42 */ 43 43 public class LayerPropertiesDialog extends JFrame{ 44 45 private Vector<String> supportedCRS;46 private ImageLayer imageLayer;47 48 private JPanel mainPanel = null;49 private JPanel jPanel = null;50 private JPanel buttonPanel = null;51 private JTabbedPane jTabbedPane = null;52 private JPanel infoPanel = null;53 private JPanel crsPanel = null;54 private JButton okButton = null;55 private JLabel layerNameLabel = null;56 private JLabel layerNameValueLabel = null;57 private JLabel imageFileLabel = null;58 private JLabel imageFileValueLabel = null;59 private JLabel sizeLabel = null;60 private JLabel sizeValueLabel = null;61 private JLabel crsLabel = null;62 private JLabel crsValueLabel = null;63 private JLabel extentLabel = null;64 private JLabel defaultCRSDescriptorLabel = null;65 private JLabel defaultCRSLabel = null;66 private JTextField searchField = null;67 private JScrollPane crsListScrollPane = null;68 private JList crsJList = null;69 private JButton useDefaultCRSButton = null;70 private JButton applySelectedCRSButton = null;71 private JButton setSelectedCRSAsDefaultButton = null;72 private JLabel searchFieldLabel = null;73 private JCheckBox eastingFirstCheckBox = null;74 private JLabel eastingFirstLabel = null;75 private JLabel tabDescriptionLabel = null;76 private JLabel upperLeftLabel = null;77 private JLabel lowerLeftLabel = null;78 private JLabel upperRightLabel = null;79 private JLabel lowerRightLabel = null;80 private JLabel upperLeftValueLabel = null;81 private JLabel upperRightValueLabel = null;82 private JLabel lowerLeftValueLabel = null;83 private JLabel lowerRightValueLabel = null;84 private JLabel currentCRSLabel = null;85 private JLabel currentCRSValueLabel = null;86 87 /**88 * This method initializes89 *90 */91 public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) {92 super(imageLayer.getName());93 this.supportedCRS = supportedCRS;94 this.imageLayer = imageLayer;95 initialize();96 }97 98 /**99 * This method initializes100 *101 */102 public LayerPropertiesDialog(Vector<String> supportedCRS) {103 super();104 this.supportedCRS = supportedCRS;105 initialize();106 }107 108 109 /**110 * This method initializes this111 *112 */113 private void initialize() {44 45 private Vector<String> supportedCRS; 46 private ImageLayer imageLayer; 47 48 private JPanel mainPanel = null; 49 private JPanel jPanel = null; 50 private JPanel buttonPanel = null; 51 private JTabbedPane jTabbedPane = null; 52 private JPanel infoPanel = null; 53 private JPanel crsPanel = null; 54 private JButton okButton = null; 55 private JLabel layerNameLabel = null; 56 private JLabel layerNameValueLabel = null; 57 private JLabel imageFileLabel = null; 58 private JLabel imageFileValueLabel = null; 59 private JLabel sizeLabel = null; 60 private JLabel sizeValueLabel = null; 61 private JLabel crsLabel = null; 62 private JLabel crsValueLabel = null; 63 private JLabel extentLabel = null; 64 private JLabel defaultCRSDescriptorLabel = null; 65 private JLabel defaultCRSLabel = null; 66 private JTextField searchField = null; 67 private JScrollPane crsListScrollPane = null; 68 private JList crsJList = null; 69 private JButton useDefaultCRSButton = null; 70 private JButton applySelectedCRSButton = null; 71 private JButton setSelectedCRSAsDefaultButton = null; 72 private JLabel searchFieldLabel = null; 73 private JCheckBox eastingFirstCheckBox = null; 74 private JLabel eastingFirstLabel = null; 75 private JLabel tabDescriptionLabel = null; 76 private JLabel upperLeftLabel = null; 77 private JLabel lowerLeftLabel = null; 78 private JLabel upperRightLabel = null; 79 private JLabel lowerRightLabel = null; 80 private JLabel upperLeftValueLabel = null; 81 private JLabel upperRightValueLabel = null; 82 private JLabel lowerLeftValueLabel = null; 83 private JLabel lowerRightValueLabel = null; 84 private JLabel currentCRSLabel = null; 85 private JLabel currentCRSValueLabel = null; 86 87 /** 88 * This method initializes 89 * 90 */ 91 public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) { 92 super(imageLayer.getName()); 93 this.supportedCRS = supportedCRS; 94 this.imageLayer = imageLayer; 95 initialize(); 96 } 97 98 /** 99 * This method initializes 100 * 101 */ 102 public LayerPropertiesDialog(Vector<String> supportedCRS) { 103 super(); 104 this.supportedCRS = supportedCRS; 105 initialize(); 106 } 107 108 109 /** 110 * This method initializes this 111 * 112 */ 113 private void initialize() { 114 114 this.setMinimumSize(new Dimension(404, 485)); 115 115 this.setContentPane(getMainPanel()); 116 116 this.setPreferredSize(new Dimension(404, 485)); 117 118 }119 120 /**121 * This method initializes mainPanel122 * 123 * @return javax.swing.JPanel124 */125 private JPanel getMainPanel() {126 if (mainPanel == null) {127 mainPanel = new JPanel();128 mainPanel.setLayout(null);129 mainPanel.add(getJPanel(), null);130 mainPanel.add(getButtonPanel(), null);131 }132 return mainPanel;133 }134 135 /**136 * This method initializes jPanel137 * 138 * @return javax.swing.JPanel139 */140 private JPanel getJPanel() {141 if (jPanel == null) {142 GridBagConstraints gridBagConstraints = new GridBagConstraints();143 gridBagConstraints.fill = GridBagConstraints.BOTH;144 gridBagConstraints.gridy = 0;145 gridBagConstraints.weightx = 1.0;146 gridBagConstraints.weighty = 1.0;147 gridBagConstraints.gridx = 0;148 jPanel = new JPanel();149 jPanel.setLayout(new GridBagLayout());150 jPanel.setBounds(new Rectangle(0, 0, 391, 406));151 jPanel.add(getJTabbedPane(), gridBagConstraints);152 }153 return jPanel;154 }155 156 /**157 * This method initializes buttonPanel158 * 159 * @return javax.swing.JPanel160 */161 private JPanel getButtonPanel() {162 if (buttonPanel == null) {163 buttonPanel = new JPanel();164 buttonPanel.setLayout(null);165 buttonPanel.setBounds(new Rectangle(0, 405, 391, 46));166 buttonPanel.add(getOkButton(), null);167 }168 return buttonPanel;169 }170 171 /**172 * This method initializes jTabbedPane173 * 174 * @return javax.swing.JTabbedPane175 */176 private JTabbedPane getJTabbedPane() {177 if (jTabbedPane == null) {178 jTabbedPane = new JTabbedPane();179 jTabbedPane.addTab("General Information", null, getInfoPanel(), null);180 jTabbedPane.addTab("Source Reference System", null, getCrsPanel(), null);181 }182 return jTabbedPane;183 }184 185 /**186 * This method initializes infoPanel187 * 188 * @return javax.swing.JPanel189 */190 private JPanel getInfoPanel() {191 if (infoPanel == null) {192 lowerRightValueLabel = new JLabel();193 lowerRightValueLabel.setBounds(new Rectangle(210, 315, 134, 16));194 lowerRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);195 lowerRightValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMaxY());196 lowerLeftValueLabel = new JLabel();197 lowerLeftValueLabel.setBounds(new Rectangle(30, 315, 133, 16));198 lowerLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);199 lowerLeftValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMinY());200 upperRightValueLabel = new JLabel();201 upperRightValueLabel.setBounds(new Rectangle(210, 255, 138, 16));202 upperRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);203 upperRightValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMaxY());204 upperLeftValueLabel = new JLabel();205 upperLeftValueLabel.setBounds(new Rectangle(30, 255, 133, 16));206 upperLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);207 upperLeftValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMinY());208 lowerRightLabel = new JLabel();209 lowerRightLabel.setBounds(new Rectangle(287, 344, 74, 16));210 lowerRightLabel.setText("Lower Right");211 upperRightLabel = new JLabel();212 upperRightLabel.setBounds(new Rectangle(285, 225, 91, 16));213 upperRightLabel.setText("Upper Right");214 lowerLeftLabel = new JLabel();215 lowerLeftLabel.setBounds(new Rectangle(15, 345, 92, 16));216 lowerLeftLabel.setText("Lower Left");217 upperLeftLabel = new JLabel();218 upperLeftLabel.setBounds(new Rectangle(15, 224, 91, 16));219 upperLeftLabel.setText("Upper Left");220 extentLabel = new JLabel();221 extentLabel.setBounds(new Rectangle(120, 195, 136, 16));222 extentLabel.setEnabled(false);223 extentLabel.setHorizontalAlignment(SwingConstants.CENTER);224 extentLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);225 extentLabel.setText("Extent");226 crsValueLabel = new JLabel();227 crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16));228 229 String crsDescription = "";230 try {231 crsDescription = imageLayer.getBbox().getCoordinateReferenceSystem().getIdentifiers().iterator().next().toString();232 } catch (Exception e) {233 }234 crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")");235 236 crsLabel = new JLabel();237 crsLabel.setBounds(new Rectangle(15, 150, 118, 16));238 crsLabel.setText("Reference System");239 sizeValueLabel = new JLabel();240 sizeValueLabel.setBounds(new Rectangle(150, 105, 226, 16));241 sizeValueLabel.setText(imageLayer.getImage().getHeight() + " x " + imageLayer.getImage().getWidth());242 sizeLabel = new JLabel();243 sizeLabel.setBounds(new Rectangle(15, 105, 121, 16));244 sizeLabel.setText("Image size");245 imageFileValueLabel = new JLabel();246 imageFileValueLabel.setBounds(new Rectangle(150, 60, 226, 16));247 imageFileValueLabel.setText(imageLayer.getImageFile().getAbsolutePath());248 imageFileValueLabel.setToolTipText(imageLayer.getImageFile().getAbsolutePath());249 imageFileLabel = new JLabel();250 imageFileLabel.setBounds(new Rectangle(15, 60, 121, 16));251 imageFileLabel.setText("Image file");252 layerNameValueLabel = new JLabel();253 layerNameValueLabel.setBounds(new Rectangle(150, 15, 226, 16));254 layerNameValueLabel.setText(imageLayer.getName());255 layerNameLabel = new JLabel();256 layerNameLabel.setBounds(new Rectangle(15, 15, 121, 16));257 layerNameLabel.setText("Layer name");258 infoPanel = new JPanel();259 infoPanel.setLayout(null);260 infoPanel.setFont(new Font("Dialog", Font.BOLD, 12));261 infoPanel.add(layerNameLabel, null);262 infoPanel.add(layerNameValueLabel, null);263 infoPanel.add(imageFileLabel, null);264 infoPanel.add(imageFileValueLabel, null);265 infoPanel.add(sizeLabel, null);266 infoPanel.add(sizeValueLabel, null);267 infoPanel.add(crsLabel, null);268 infoPanel.add(crsValueLabel, null);269 infoPanel.add(extentLabel, null);270 infoPanel.add(upperLeftLabel, null);271 infoPanel.add(lowerLeftLabel, null);272 infoPanel.add(upperRightLabel, null);273 infoPanel.add(lowerRightLabel, null);274 infoPanel.add(upperLeftValueLabel, null);275 infoPanel.add(upperRightValueLabel, null);276 infoPanel.add(lowerLeftValueLabel, null);277 infoPanel.add(lowerRightValueLabel, null);278 }279 return infoPanel;280 }281 282 /**283 * This method initializes crsPanel284 * 285 * @return javax.swing.JPanel286 */287 private JPanel getCrsPanel() {288 if (crsPanel == null) {289 currentCRSValueLabel = new JLabel();290 currentCRSValueLabel.setBounds(new Rectangle(78, 33, 297, 16));291 String crsDescription = "unknown";292 try {293 crsDescription = imageLayer.getSourceRefSys().getIdentifiers().iterator().next().toString();294 } catch (Exception e) {295 }296 currentCRSValueLabel.setText(crsDescription);297 298 currentCRSLabel = new JLabel();299 currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16));300 currentCRSLabel.setText("Current:");301 tabDescriptionLabel = new JLabel();302 tabDescriptionLabel.setBounds(new Rectangle(15, 9, 361, 16));303 tabDescriptionLabel.setText("Set here the source reference system of the image");304 eastingFirstLabel = new JLabel();305 eastingFirstLabel.setBounds(new Rectangle(315, 210, 76, 46));306 eastingFirstLabel.setHorizontalTextPosition(SwingConstants.TRAILING);307 eastingFirstLabel.setHorizontalAlignment(SwingConstants.CENTER);308 eastingFirstLabel.setText("<html>Easting<br>first</html>");309 searchFieldLabel = new JLabel();310 searchFieldLabel.setBounds(new Rectangle(298, 114, 84, 16));311 searchFieldLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);312 searchFieldLabel.setHorizontalTextPosition(SwingConstants.TRAILING);313 searchFieldLabel.setHorizontalAlignment(SwingConstants.CENTER);314 searchFieldLabel.setText("Search");315 defaultCRSLabel = new JLabel();316 defaultCRSLabel.setBounds(new Rectangle(15, 89, 361, 16));317 defaultCRSLabel.setText(PluginOperations.defaultSourceCRSDescription);318 defaultCRSDescriptorLabel = new JLabel();319 defaultCRSDescriptorLabel.setBounds(new Rectangle(15, 63, 226, 16));320 defaultCRSDescriptorLabel.setText("Default Reference System:");321 crsPanel = new JPanel();322 crsPanel.setLayout(null);323 crsPanel.add(defaultCRSDescriptorLabel, null);324 crsPanel.add(defaultCRSLabel, null);325 crsPanel.add(getSearchField(), null);326 crsPanel.add(getCrsListScrollPane(), null);327 crsPanel.add(getUseDefaultCRSButton(), null);328 crsPanel.add(getApplySelectedCRSButton(), null);329 crsPanel.add(getSetSelectedCRSAsDefaultButton(), null);330 crsPanel.add(searchFieldLabel, null);331 crsPanel.add(getEastingFirstCheckBox(), null);332 crsPanel.add(eastingFirstLabel, null);333 crsPanel.add(tabDescriptionLabel, null);334 crsPanel.add(currentCRSLabel, null);335 crsPanel.add(currentCRSValueLabel, null);336 }337 return crsPanel;338 }339 340 /**341 * This method initializes okButton342 * 343 * @return javax.swing.JButton344 */345 private JButton getOkButton() {346 if (okButton == null) {347 okButton = new JButton();348 okButton.setBounds(new Rectangle(134, 5, 136, 31));349 okButton.setText("OK");350 okButton.addActionListener(new java.awt.event.ActionListener() {351 public void actionPerformed(java.awt.event.ActionEvent e) {352 353 setVisible(false);354 dispose();355 }356 });357 }358 return okButton;359 }360 361 /**362 * This method initializes searchField363 * 364 * @return javax.swing.JTextField365 */366 private JTextField getSearchField() {367 if (searchField == null) {368 searchField = new JTextField();369 searchField.setBounds(new Rectangle(13, 111, 282, 20));370 searchField.setToolTipText("Enter keywords or EPSG codes");371 searchField.addKeyListener(new java.awt.event.KeyAdapter() {372 public void keyTyped(java.awt.event.KeyEvent e) {373 374 for (Iterator iterator = supportedCRS.iterator(); iterator375 .hasNext();) {376 String type = (String) iterator.next();377 if(type.contains(searchField.getText()))378 {379 crsJList.setSelectedIndex(supportedCRS.indexOf(type));380 crsJList.ensureIndexIsVisible(supportedCRS.indexOf(type));381 break;382 }383 384 }385 }386 });387 }388 return searchField;389 }390 391 /**392 * This method initializes crsListScrollPane393 * 394 * @return javax.swing.JScrollPane395 */396 private JScrollPane getCrsListScrollPane() {397 if (crsListScrollPane == null) {398 crsListScrollPane = new JScrollPane();399 crsListScrollPane.setBounds(new Rectangle(15, 135, 301, 241));400 crsListScrollPane.setViewportView(getCrsJList());401 }402 return crsListScrollPane;403 }404 405 /**406 * This method initializes crsJList407 * 408 * @return javax.swing.JList409 */410 private JList getCrsJList() {411 if (crsJList == null) {412 crsJList = new JList(supportedCRS);413 crsJList.addListSelectionListener(new ListSelectionHandler());414 }415 return crsJList;416 }417 418 /**419 * This method initializes useDefaultCRSButton420 * 421 * @return javax.swing.JButton422 */423 private JButton getUseDefaultCRSButton() {424 if (useDefaultCRSButton == null) {425 useDefaultCRSButton = new JButton();426 useDefaultCRSButton.setBounds(new Rectangle(253, 54, 118, 28));427 useDefaultCRSButton.setText("Apply Default");428 useDefaultCRSButton.addActionListener(new java.awt.event.ActionListener() {429 public void actionPerformed(java.awt.event.ActionEvent e) {430 431 try {432 433 setCursor(new Cursor(Cursor.WAIT_CURSOR));434 if(PluginOperations.defaultSourceCRS != null){435 imageLayer.resample(PluginOperations.defaultSourceCRS);436 }else437 {438 JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>");439 }440 441 } catch (NoSuchAuthorityCodeException e1) {442 // TODO Auto-generated catch block443 e1.printStackTrace();444 } catch (FactoryException e1) {445 // TODO Auto-generated catch block446 e1.printStackTrace();447 } catch (IOException e2) {448 // TODO Auto-generated catch block449 e2.printStackTrace();450 }451 finally{452 setCursor(new Cursor(Cursor.DEFAULT_CURSOR));453 }454 }455 });456 }457 return useDefaultCRSButton;458 }459 460 /**461 * This method initializes applySelectedCRSButton462 * 463 * @return javax.swing.JButton464 */465 private JButton getApplySelectedCRSButton() {466 if (applySelectedCRSButton == null) {467 applySelectedCRSButton = new JButton();468 applySelectedCRSButton.setBounds(new Rectangle(315, 135, 69, 61));469 applySelectedCRSButton.setHorizontalAlignment(SwingConstants.CENTER);470 applySelectedCRSButton.setHorizontalTextPosition(SwingConstants.TRAILING);471 applySelectedCRSButton.setText("<html>Apply<br>Selection</html>");472 applySelectedCRSButton.addActionListener(new java.awt.event.ActionListener() {473 public void actionPerformed(java.awt.event.ActionEvent e) {474 475 String selection = (String) crsJList.getSelectedValue();476 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));477 478 CoordinateReferenceSystem newRefSys = null;479 try {480 newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected());481 482 setCursor(new Cursor(Cursor.WAIT_CURSOR));483 484 imageLayer.resample(newRefSys);485 486 } catch (NoSuchAuthorityCodeException e1) {487 // TODO Auto-generated catch block488 e1.printStackTrace();489 } catch (FactoryException e1) {490 // TODO Auto-generated catch block491 e1.printStackTrace();492 } catch (IOException e2) {493 // TODO Auto-generated catch block494 e2.printStackTrace();495 }496 finally{497 setCursor(new Cursor(Cursor.DEFAULT_CURSOR));498 }499 500 501 }502 });503 }504 return applySelectedCRSButton;505 }506 507 /**508 * This method initializes setSelectedCRSAsDefaultButton509 * 510 * @return javax.swing.JButton511 */512 private JButton getSetSelectedCRSAsDefaultButton() {513 if (setSelectedCRSAsDefaultButton == null) {514 setSelectedCRSAsDefaultButton = new JButton();515 setSelectedCRSAsDefaultButton.setBounds(new Rectangle(315, 300, 69, 61));516 setSelectedCRSAsDefaultButton.setText("<html>Set as<br>Default</html>");517 setSelectedCRSAsDefaultButton518 .addActionListener(new java.awt.event.ActionListener() {519 public void actionPerformed(java.awt.event.ActionEvent e) {520 521 if(crsJList.getSelectedValue() != null){522 String selection = (String) crsJList.getSelectedValue();523 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));524 525 try {526 PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected());527 PluginOperations.defaultSourceCRSDescription = selection;528 529 ImageImportPlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected());530 ImageImportPlugin.pluginProps.setProperty("default_crs_srid", code);531 FileWriter fileWriter = new FileWriter(new File(ImageImportPlugin.PLUGINPROPERTIES_PATH));532 ImageImportPlugin.pluginProps.store(fileWriter, null);533 fileWriter.close();534 535 defaultCRSLabel.setText(selection);536 537 } catch (IOException e2) {538 // TODO Auto-generated catch block539 e2.printStackTrace();540 } catch (NoSuchAuthorityCodeException e3) {541 // TODO Auto-generated catch block542 e3.printStackTrace();543 } catch (FactoryException e4) {544 // TODO Auto-generated catch block545 e4.printStackTrace();546 }547 }else{548 JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list.");549 }550 551 552 }553 });554 }555 return setSelectedCRSAsDefaultButton;556 }557 558 /**559 * This method initializes eastingFirstCheckBox560 * 561 * @return javax.swing.JCheckBox562 */563 private JCheckBox getEastingFirstCheckBox() {564 if (eastingFirstCheckBox == null) {565 eastingFirstCheckBox = new JCheckBox();566 eastingFirstCheckBox.setBounds(new Rectangle(345, 255, 21, 21));567 }568 return eastingFirstCheckBox;569 }570 571 572 573 /**574 * Listener setting text in the search field if selection has changed.575 *576 */117 118 } 119 120 /** 121 * This method initializes mainPanel 122 * 123 * @return javax.swing.JPanel 124 */ 125 private JPanel getMainPanel() { 126 if (mainPanel == null) { 127 mainPanel = new JPanel(); 128 mainPanel.setLayout(null); 129 mainPanel.add(getJPanel(), null); 130 mainPanel.add(getButtonPanel(), null); 131 } 132 return mainPanel; 133 } 134 135 /** 136 * This method initializes jPanel 137 * 138 * @return javax.swing.JPanel 139 */ 140 private JPanel getJPanel() { 141 if (jPanel == null) { 142 GridBagConstraints gridBagConstraints = new GridBagConstraints(); 143 gridBagConstraints.fill = GridBagConstraints.BOTH; 144 gridBagConstraints.gridy = 0; 145 gridBagConstraints.weightx = 1.0; 146 gridBagConstraints.weighty = 1.0; 147 gridBagConstraints.gridx = 0; 148 jPanel = new JPanel(); 149 jPanel.setLayout(new GridBagLayout()); 150 jPanel.setBounds(new Rectangle(0, 0, 391, 406)); 151 jPanel.add(getJTabbedPane(), gridBagConstraints); 152 } 153 return jPanel; 154 } 155 156 /** 157 * This method initializes buttonPanel 158 * 159 * @return javax.swing.JPanel 160 */ 161 private JPanel getButtonPanel() { 162 if (buttonPanel == null) { 163 buttonPanel = new JPanel(); 164 buttonPanel.setLayout(null); 165 buttonPanel.setBounds(new Rectangle(0, 405, 391, 46)); 166 buttonPanel.add(getOkButton(), null); 167 } 168 return buttonPanel; 169 } 170 171 /** 172 * This method initializes jTabbedPane 173 * 174 * @return javax.swing.JTabbedPane 175 */ 176 private JTabbedPane getJTabbedPane() { 177 if (jTabbedPane == null) { 178 jTabbedPane = new JTabbedPane(); 179 jTabbedPane.addTab("General Information", null, getInfoPanel(), null); 180 jTabbedPane.addTab("Source Reference System", null, getCrsPanel(), null); 181 } 182 return jTabbedPane; 183 } 184 185 /** 186 * This method initializes infoPanel 187 * 188 * @return javax.swing.JPanel 189 */ 190 private JPanel getInfoPanel() { 191 if (infoPanel == null) { 192 lowerRightValueLabel = new JLabel(); 193 lowerRightValueLabel.setBounds(new Rectangle(210, 315, 134, 16)); 194 lowerRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT); 195 lowerRightValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMaxY()); 196 lowerLeftValueLabel = new JLabel(); 197 lowerLeftValueLabel.setBounds(new Rectangle(30, 315, 133, 16)); 198 lowerLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT); 199 lowerLeftValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMinY()); 200 upperRightValueLabel = new JLabel(); 201 upperRightValueLabel.setBounds(new Rectangle(210, 255, 138, 16)); 202 upperRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT); 203 upperRightValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMaxY()); 204 upperLeftValueLabel = new JLabel(); 205 upperLeftValueLabel.setBounds(new Rectangle(30, 255, 133, 16)); 206 upperLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT); 207 upperLeftValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMinY()); 208 lowerRightLabel = new JLabel(); 209 lowerRightLabel.setBounds(new Rectangle(287, 344, 74, 16)); 210 lowerRightLabel.setText("Lower Right"); 211 upperRightLabel = new JLabel(); 212 upperRightLabel.setBounds(new Rectangle(285, 225, 91, 16)); 213 upperRightLabel.setText("Upper Right"); 214 lowerLeftLabel = new JLabel(); 215 lowerLeftLabel.setBounds(new Rectangle(15, 345, 92, 16)); 216 lowerLeftLabel.setText("Lower Left"); 217 upperLeftLabel = new JLabel(); 218 upperLeftLabel.setBounds(new Rectangle(15, 224, 91, 16)); 219 upperLeftLabel.setText("Upper Left"); 220 extentLabel = new JLabel(); 221 extentLabel.setBounds(new Rectangle(120, 195, 136, 16)); 222 extentLabel.setEnabled(false); 223 extentLabel.setHorizontalAlignment(SwingConstants.CENTER); 224 extentLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED); 225 extentLabel.setText("Extent"); 226 crsValueLabel = new JLabel(); 227 crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16)); 228 229 String crsDescription = ""; 230 try { 231 crsDescription = imageLayer.getBbox().getCoordinateReferenceSystem().getIdentifiers().iterator().next().toString(); 232 } catch (Exception e) { 233 } 234 crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")"); 235 236 crsLabel = new JLabel(); 237 crsLabel.setBounds(new Rectangle(15, 150, 118, 16)); 238 crsLabel.setText("Reference System"); 239 sizeValueLabel = new JLabel(); 240 sizeValueLabel.setBounds(new Rectangle(150, 105, 226, 16)); 241 sizeValueLabel.setText(imageLayer.getImage().getHeight() + " x " + imageLayer.getImage().getWidth()); 242 sizeLabel = new JLabel(); 243 sizeLabel.setBounds(new Rectangle(15, 105, 121, 16)); 244 sizeLabel.setText("Image size"); 245 imageFileValueLabel = new JLabel(); 246 imageFileValueLabel.setBounds(new Rectangle(150, 60, 226, 16)); 247 imageFileValueLabel.setText(imageLayer.getImageFile().getAbsolutePath()); 248 imageFileValueLabel.setToolTipText(imageLayer.getImageFile().getAbsolutePath()); 249 imageFileLabel = new JLabel(); 250 imageFileLabel.setBounds(new Rectangle(15, 60, 121, 16)); 251 imageFileLabel.setText("Image file"); 252 layerNameValueLabel = new JLabel(); 253 layerNameValueLabel.setBounds(new Rectangle(150, 15, 226, 16)); 254 layerNameValueLabel.setText(imageLayer.getName()); 255 layerNameLabel = new JLabel(); 256 layerNameLabel.setBounds(new Rectangle(15, 15, 121, 16)); 257 layerNameLabel.setText("Layer name"); 258 infoPanel = new JPanel(); 259 infoPanel.setLayout(null); 260 infoPanel.setFont(new Font("Dialog", Font.BOLD, 12)); 261 infoPanel.add(layerNameLabel, null); 262 infoPanel.add(layerNameValueLabel, null); 263 infoPanel.add(imageFileLabel, null); 264 infoPanel.add(imageFileValueLabel, null); 265 infoPanel.add(sizeLabel, null); 266 infoPanel.add(sizeValueLabel, null); 267 infoPanel.add(crsLabel, null); 268 infoPanel.add(crsValueLabel, null); 269 infoPanel.add(extentLabel, null); 270 infoPanel.add(upperLeftLabel, null); 271 infoPanel.add(lowerLeftLabel, null); 272 infoPanel.add(upperRightLabel, null); 273 infoPanel.add(lowerRightLabel, null); 274 infoPanel.add(upperLeftValueLabel, null); 275 infoPanel.add(upperRightValueLabel, null); 276 infoPanel.add(lowerLeftValueLabel, null); 277 infoPanel.add(lowerRightValueLabel, null); 278 } 279 return infoPanel; 280 } 281 282 /** 283 * This method initializes crsPanel 284 * 285 * @return javax.swing.JPanel 286 */ 287 private JPanel getCrsPanel() { 288 if (crsPanel == null) { 289 currentCRSValueLabel = new JLabel(); 290 currentCRSValueLabel.setBounds(new Rectangle(78, 33, 297, 16)); 291 String crsDescription = "unknown"; 292 try { 293 crsDescription = imageLayer.getSourceRefSys().getIdentifiers().iterator().next().toString(); 294 } catch (Exception e) { 295 } 296 currentCRSValueLabel.setText(crsDescription); 297 298 currentCRSLabel = new JLabel(); 299 currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16)); 300 currentCRSLabel.setText("Current:"); 301 tabDescriptionLabel = new JLabel(); 302 tabDescriptionLabel.setBounds(new Rectangle(15, 9, 361, 16)); 303 tabDescriptionLabel.setText("Set here the source reference system of the image"); 304 eastingFirstLabel = new JLabel(); 305 eastingFirstLabel.setBounds(new Rectangle(315, 210, 76, 46)); 306 eastingFirstLabel.setHorizontalTextPosition(SwingConstants.TRAILING); 307 eastingFirstLabel.setHorizontalAlignment(SwingConstants.CENTER); 308 eastingFirstLabel.setText("<html>Easting<br>first</html>"); 309 searchFieldLabel = new JLabel(); 310 searchFieldLabel.setBounds(new Rectangle(298, 114, 84, 16)); 311 searchFieldLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED); 312 searchFieldLabel.setHorizontalTextPosition(SwingConstants.TRAILING); 313 searchFieldLabel.setHorizontalAlignment(SwingConstants.CENTER); 314 searchFieldLabel.setText("Search"); 315 defaultCRSLabel = new JLabel(); 316 defaultCRSLabel.setBounds(new Rectangle(15, 89, 361, 16)); 317 defaultCRSLabel.setText(PluginOperations.defaultSourceCRSDescription); 318 defaultCRSDescriptorLabel = new JLabel(); 319 defaultCRSDescriptorLabel.setBounds(new Rectangle(15, 63, 226, 16)); 320 defaultCRSDescriptorLabel.setText("Default Reference System:"); 321 crsPanel = new JPanel(); 322 crsPanel.setLayout(null); 323 crsPanel.add(defaultCRSDescriptorLabel, null); 324 crsPanel.add(defaultCRSLabel, null); 325 crsPanel.add(getSearchField(), null); 326 crsPanel.add(getCrsListScrollPane(), null); 327 crsPanel.add(getUseDefaultCRSButton(), null); 328 crsPanel.add(getApplySelectedCRSButton(), null); 329 crsPanel.add(getSetSelectedCRSAsDefaultButton(), null); 330 crsPanel.add(searchFieldLabel, null); 331 crsPanel.add(getEastingFirstCheckBox(), null); 332 crsPanel.add(eastingFirstLabel, null); 333 crsPanel.add(tabDescriptionLabel, null); 334 crsPanel.add(currentCRSLabel, null); 335 crsPanel.add(currentCRSValueLabel, null); 336 } 337 return crsPanel; 338 } 339 340 /** 341 * This method initializes okButton 342 * 343 * @return javax.swing.JButton 344 */ 345 private JButton getOkButton() { 346 if (okButton == null) { 347 okButton = new JButton(); 348 okButton.setBounds(new Rectangle(134, 5, 136, 31)); 349 okButton.setText("OK"); 350 okButton.addActionListener(new java.awt.event.ActionListener() { 351 public void actionPerformed(java.awt.event.ActionEvent e) { 352 353 setVisible(false); 354 dispose(); 355 } 356 }); 357 } 358 return okButton; 359 } 360 361 /** 362 * This method initializes searchField 363 * 364 * @return javax.swing.JTextField 365 */ 366 private JTextField getSearchField() { 367 if (searchField == null) { 368 searchField = new JTextField(); 369 searchField.setBounds(new Rectangle(13, 111, 282, 20)); 370 searchField.setToolTipText("Enter keywords or EPSG codes"); 371 searchField.addKeyListener(new java.awt.event.KeyAdapter() { 372 public void keyTyped(java.awt.event.KeyEvent e) { 373 374 for (Iterator iterator = supportedCRS.iterator(); iterator 375 .hasNext();) { 376 String type = (String) iterator.next(); 377 if(type.contains(searchField.getText())) 378 { 379 crsJList.setSelectedIndex(supportedCRS.indexOf(type)); 380 crsJList.ensureIndexIsVisible(supportedCRS.indexOf(type)); 381 break; 382 } 383 384 } 385 } 386 }); 387 } 388 return searchField; 389 } 390 391 /** 392 * This method initializes crsListScrollPane 393 * 394 * @return javax.swing.JScrollPane 395 */ 396 private JScrollPane getCrsListScrollPane() { 397 if (crsListScrollPane == null) { 398 crsListScrollPane = new JScrollPane(); 399 crsListScrollPane.setBounds(new Rectangle(15, 135, 301, 241)); 400 crsListScrollPane.setViewportView(getCrsJList()); 401 } 402 return crsListScrollPane; 403 } 404 405 /** 406 * This method initializes crsJList 407 * 408 * @return javax.swing.JList 409 */ 410 private JList getCrsJList() { 411 if (crsJList == null) { 412 crsJList = new JList(supportedCRS); 413 crsJList.addListSelectionListener(new ListSelectionHandler()); 414 } 415 return crsJList; 416 } 417 418 /** 419 * This method initializes useDefaultCRSButton 420 * 421 * @return javax.swing.JButton 422 */ 423 private JButton getUseDefaultCRSButton() { 424 if (useDefaultCRSButton == null) { 425 useDefaultCRSButton = new JButton(); 426 useDefaultCRSButton.setBounds(new Rectangle(253, 54, 118, 28)); 427 useDefaultCRSButton.setText("Apply Default"); 428 useDefaultCRSButton.addActionListener(new java.awt.event.ActionListener() { 429 public void actionPerformed(java.awt.event.ActionEvent e) { 430 431 try { 432 433 setCursor(new Cursor(Cursor.WAIT_CURSOR)); 434 if(PluginOperations.defaultSourceCRS != null){ 435 imageLayer.resample(PluginOperations.defaultSourceCRS); 436 }else 437 { 438 JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>"); 439 } 440 441 } catch (NoSuchAuthorityCodeException e1) { 442 // TODO Auto-generated catch block 443 e1.printStackTrace(); 444 } catch (FactoryException e1) { 445 // TODO Auto-generated catch block 446 e1.printStackTrace(); 447 } catch (IOException e2) { 448 // TODO Auto-generated catch block 449 e2.printStackTrace(); 450 } 451 finally{ 452 setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 453 } 454 } 455 }); 456 } 457 return useDefaultCRSButton; 458 } 459 460 /** 461 * This method initializes applySelectedCRSButton 462 * 463 * @return javax.swing.JButton 464 */ 465 private JButton getApplySelectedCRSButton() { 466 if (applySelectedCRSButton == null) { 467 applySelectedCRSButton = new JButton(); 468 applySelectedCRSButton.setBounds(new Rectangle(315, 135, 69, 61)); 469 applySelectedCRSButton.setHorizontalAlignment(SwingConstants.CENTER); 470 applySelectedCRSButton.setHorizontalTextPosition(SwingConstants.TRAILING); 471 applySelectedCRSButton.setText("<html>Apply<br>Selection</html>"); 472 applySelectedCRSButton.addActionListener(new java.awt.event.ActionListener() { 473 public void actionPerformed(java.awt.event.ActionEvent e) { 474 475 String selection = (String) crsJList.getSelectedValue(); 476 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]")); 477 478 CoordinateReferenceSystem newRefSys = null; 479 try { 480 newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected()); 481 482 setCursor(new Cursor(Cursor.WAIT_CURSOR)); 483 484 imageLayer.resample(newRefSys); 485 486 } catch (NoSuchAuthorityCodeException e1) { 487 // TODO Auto-generated catch block 488 e1.printStackTrace(); 489 } catch (FactoryException e1) { 490 // TODO Auto-generated catch block 491 e1.printStackTrace(); 492 } catch (IOException e2) { 493 // TODO Auto-generated catch block 494 e2.printStackTrace(); 495 } 496 finally{ 497 setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 498 } 499 500 501 } 502 }); 503 } 504 return applySelectedCRSButton; 505 } 506 507 /** 508 * This method initializes setSelectedCRSAsDefaultButton 509 * 510 * @return javax.swing.JButton 511 */ 512 private JButton getSetSelectedCRSAsDefaultButton() { 513 if (setSelectedCRSAsDefaultButton == null) { 514 setSelectedCRSAsDefaultButton = new JButton(); 515 setSelectedCRSAsDefaultButton.setBounds(new Rectangle(315, 300, 69, 61)); 516 setSelectedCRSAsDefaultButton.setText("<html>Set as<br>Default</html>"); 517 setSelectedCRSAsDefaultButton 518 .addActionListener(new java.awt.event.ActionListener() { 519 public void actionPerformed(java.awt.event.ActionEvent e) { 520 521 if(crsJList.getSelectedValue() != null){ 522 String selection = (String) crsJList.getSelectedValue(); 523 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]")); 524 525 try { 526 PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected()); 527 PluginOperations.defaultSourceCRSDescription = selection; 528 529 ImageImportPlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected()); 530 ImageImportPlugin.pluginProps.setProperty("default_crs_srid", code); 531 FileWriter fileWriter = new FileWriter(new File(ImageImportPlugin.PLUGINPROPERTIES_PATH)); 532 ImageImportPlugin.pluginProps.store(fileWriter, null); 533 fileWriter.close(); 534 535 defaultCRSLabel.setText(selection); 536 537 } catch (IOException e2) { 538 // TODO Auto-generated catch block 539 e2.printStackTrace(); 540 } catch (NoSuchAuthorityCodeException e3) { 541 // TODO Auto-generated catch block 542 e3.printStackTrace(); 543 } catch (FactoryException e4) { 544 // TODO Auto-generated catch block 545 e4.printStackTrace(); 546 } 547 }else{ 548 JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list."); 549 } 550 551 552 } 553 }); 554 } 555 return setSelectedCRSAsDefaultButton; 556 } 557 558 /** 559 * This method initializes eastingFirstCheckBox 560 * 561 * @return javax.swing.JCheckBox 562 */ 563 private JCheckBox getEastingFirstCheckBox() { 564 if (eastingFirstCheckBox == null) { 565 eastingFirstCheckBox = new JCheckBox(); 566 eastingFirstCheckBox.setBounds(new Rectangle(345, 255, 21, 21)); 567 } 568 return eastingFirstCheckBox; 569 } 570 571 572 573 /** 574 * Listener setting text in the search field if selection has changed. 575 * 576 */ 577 577 class ListSelectionHandler implements ListSelectionListener { 578 578 public void valueChanged(ListSelectionEvent e) { 579 if(e.getValueIsAdjusting())580 {581 searchField.setText(supportedCRS.get(e.getLastIndex()));582 searchField.setEditable(true);583 }579 if(e.getValueIsAdjusting()) 580 { 581 searchField.setText(supportedCRS.get(e.getLastIndex())); 582 searchField.setEditable(true); 583 } 584 584 } 585 585 } -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LoadImageAction.java
r23145 r23187 26 26 */ 27 27 public class LoadImageAction extends JosmAction { 28 29 private Logger logger = Logger.getLogger(LoadImageAction.class);28 29 private Logger logger = Logger.getLogger(LoadImageAction.class); 30 30 31 /**32 * Constructor...33 */34 public LoadImageAction() {35 super(tr("Import image"), null, tr("Import georeferenced image"), null, false);36 }31 /** 32 * Constructor... 33 */ 34 public LoadImageAction() { 35 super(tr("Import image"), null, tr("Import georeferenced image"), null, false); 36 } 37 37 38 public void actionPerformed(ActionEvent arg0) {38 public void actionPerformed(ActionEvent arg0) { 39 39 40 // Choose a file41 JFileChooser fc = new JFileChooser();42 fc.setAcceptAllFileFilterUsed(false);43 int result = fc.showOpenDialog(Main.parent);44 45 ImageLayer layer = null;46 if (result == JFileChooser.APPROVE_OPTION) {47 logger.info("File choosed:" + fc.getSelectedFile());48 try {49 layer = new ImageLayer(fc.getSelectedFile());50 } catch (LayerCreationCancledException e) {51 // if user decides that layer should not be created just return.52 return;53 }catch (Exception e) {54 logger.error("Error while creating image layer: \n" + e.getMessage());55 JOptionPane.showMessageDialog(null, marktr("Error while creating image layer: " + e.getCause()));56 return;57 58 }59 60 // Add layer:61 Main.main.addLayer(layer);62 LatLon min = new LatLon(layer.getBbox().getMinX(), layer.getBbox().getMinY());63 LatLon max = new LatLon(layer.getBbox().getMaxX(), layer.getBbox().getMaxY());64 BoundingXYVisitor boundingXYVisitor = new BoundingXYVisitor();65 boundingXYVisitor.visit(new Bounds(min, max));66 Main.map.mapView.recalculateCenterScale(boundingXYVisitor);67 Main.map.mapView.zoomTo(new Bounds(min, max));68 }69 }40 // Choose a file 41 JFileChooser fc = new JFileChooser(); 42 fc.setAcceptAllFileFilterUsed(false); 43 int result = fc.showOpenDialog(Main.parent); 44 45 ImageLayer layer = null; 46 if (result == JFileChooser.APPROVE_OPTION) { 47 logger.info("File choosed:" + fc.getSelectedFile()); 48 try { 49 layer = new ImageLayer(fc.getSelectedFile()); 50 } catch (LayerCreationCancledException e) { 51 // if user decides that layer should not be created just return. 52 return; 53 }catch (Exception e) { 54 logger.error("Error while creating image layer: \n" + e.getMessage()); 55 JOptionPane.showMessageDialog(null, marktr("Error while creating image layer: " + e.getCause())); 56 return; 57 58 } 59 60 // Add layer: 61 Main.main.addLayer(layer); 62 LatLon min = new LatLon(layer.getBbox().getMinX(), layer.getBbox().getMinY()); 63 LatLon max = new LatLon(layer.getBbox().getMaxX(), layer.getBbox().getMaxY()); 64 BoundingXYVisitor boundingXYVisitor = new BoundingXYVisitor(); 65 boundingXYVisitor.visit(new Bounds(min, max)); 66 Main.map.mapView.recalculateCenterScale(boundingXYVisitor); 67 Main.map.mapView.zoomTo(new Bounds(min, max)); 68 } 69 } 70 70 } -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java
r23145 r23187 47 47 public class PluginOperations { 48 48 49 private static final Logger logger = Logger.getLogger(PluginOperations.class);50 51 // contains descriptions of all available CRS52 static Vector<String> crsDescriptions;53 54 // the standard native CRS of user images55 static CoordinateReferenceSystem defaultSourceCRS;56 // description of 'defaultSourceCRS'57 static String defaultSourceCRSDescription;58 59 60 61 public static enum SUPPORTEDIMAGETYPES {62 tiff, tif, jpg, jpeg, bmp, png63 }64 65 public static enum POSTFIXES_WORLDFILE {66 wld, jgw, jpgw, pgw, pngw, tfw, tifw, bpw, bmpw,67 };68 69 /**70 * Reprojects a GridCoverage to a given CRS.71 *72 * @param coverage73 * @param targetCrs74 * @return destination75 * @throws FactoryException76 * @throws NoSuchAuthorityCodeException77 */78 public static GridCoverage2D reprojectCoverage(GridCoverage2D coverage,79 CoordinateReferenceSystem targetCrs) throws NoSuchAuthorityCodeException, FactoryException {80 81 // TODO: add category for NO_DATA values in coverage (transparency in82 // image)83 84 GridCoverage2D destination = null;85 86 DefaultProcessor processor = new DefaultProcessor(null);87 ParameterValueGroup resampleParams = processor.getOperation("Resample")88 .getParameters();89 90 // set parameters91 resampleParams.parameter("Source").setValue(coverage);92 resampleParams.parameter("CoordinateReferenceSystem").setValue(93 targetCrs);94 95 // resample coverage with given parameters96 destination = (GridCoverage2D) processor.doOperation(resampleParams);97 98 return destination;99 }100 101 /**102 * Creates a org.geotools.coverage.grid.GridCoverage2D from a given file.103 *104 * @param file105 * @return106 * @throws IOException107 * @throws Exception108 */109 public static GridCoverage2D createGridFromFile(File file, CoordinateReferenceSystem refSys) throws IOException{110 111 GridCoverage2D coverage = null;112 113 if (!file.exists()) throw new FileNotFoundException("File not found.");114 115 String extension = null;116 String fileNameWithoutExt = null;117 int dotPos = file.getAbsolutePath().lastIndexOf(".");118 extension = file.getAbsolutePath().substring(dotPos);119 fileNameWithoutExt = file.getAbsolutePath().substring(0, dotPos);120 121 /*------- switch for file type -----------*/122 if (extension.equalsIgnoreCase(".tif")123 || extension.equalsIgnoreCase(".tiff"))124 {125 126 // try to read GeoTIFF:127 try{128 coverage = readGeoTiff(file, refSys);129 return coverage;130 }catch (DataSourceException dse) {131 if(!dse.getMessage().contains("Coordinate Reference System is not available")){132 dse.printStackTrace();133 }134 } catch (FactoryException facte) {135 logger.fatal("Error while reading from GeoTIFF:", facte);136 throw new IOException(facte);137 }138 139 // file is no GeoTiff, searching for Worldfile and projection file:140 String[] postfixes = {"wld", "tfw", "tifw"};141 // try to read Worldfile:142 WorldFileReader tfwReader = null;143 for (int i = 0; i < postfixes.length; i++) {144 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);145 if(prjFile.exists()){146 tfwReader = new WorldFileReader(prjFile);147 }148 }149 if(tfwReader == null){150 throw new IOException("No Worldfile found.");151 }152 153 if(refSys == null){154 // if no crs is delivered try to read projection file:155 refSys = readPrjFile(file);156 if(refSys == null) throw new IOException("No projection file found.");157 }158 159 BufferedImage img = ImageIO.read(file);160 161 // create Envelope162 double width = (double) (img.getWidth() * tfwReader.getXPixelSize());163 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));164 double lowerLeft_x = (double) tfwReader.getXULC();165 double lowerLeft_y = (double) tfwReader.getYULC() - height;166 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));167 168 coverage = createGridCoverage(img, bbox, refSys);169 170 }171 //172 else if (extension.equalsIgnoreCase(".jpg")173 || extension.equalsIgnoreCase(".jpeg"))174 {175 String[] postfixes = {"wld", "jgw", "jpgw"};176 // try to read Worldfile:177 WorldFileReader tfwReader = null;178 for (int i = 0; i < postfixes.length; i++) {179 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);180 if(prjFile.exists()){181 tfwReader = new WorldFileReader(prjFile);182 }183 }184 if(tfwReader == null) throw new IOException("No Worldfile found.");185 186 if(refSys == null){187 // if no crs is delivered try to read projection file:188 refSys = readPrjFile(file);189 if(refSys == null) throw new IOException("No projection file found.");190 }191 192 BufferedImage img = ImageIO.read(file);193 194 // create Envelope195 double width = (double) (img.getWidth() * tfwReader.getXPixelSize());196 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));197 double lowerLeft_x = (double) tfwReader.getXULC();198 double lowerLeft_y = (double) tfwReader.getYULC() - height;199 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));200 201 coverage = createGridCoverage(img, bbox, refSys);202 203 }204 else if(extension.equalsIgnoreCase(".bmp"))205 {206 String[] postfixes = {"wld", "bmpw", "bpw"};207 // try to read Worldfile:208 WorldFileReader tfwReader = null;209 for (int i = 0; i < postfixes.length; i++) {210 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);211 if(prjFile.exists()){212 tfwReader = new WorldFileReader(prjFile);213 }214 }215 if(tfwReader == null) throw new IOException("No Worldfile found.");216 217 if(refSys == null){218 // if no crs is delivered try to read projection file:219 refSys = readPrjFile(file);220 if(refSys == null) throw new IOException("No projection file found.");221 }222 223 BufferedImage img = ImageIO.read(file);224 225 // create Envelope226 double width = (double) (img.getWidth() * tfwReader.getXPixelSize());227 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));228 double lowerLeft_x = (double) tfwReader.getXULC();229 double lowerLeft_y = (double) tfwReader.getYULC() - height;230 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));231 232 coverage = createGridCoverage(img, bbox, refSys);233 }234 else if(extension.equalsIgnoreCase(".png"))235 {236 237 String[] postfixes = {"wld", "pgw", "pngw"};238 // try to read Worldfile:239 WorldFileReader tfwReader = null;240 for (int i = 0; i < postfixes.length; i++) {241 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);242 if(prjFile.exists()){243 tfwReader = new WorldFileReader(prjFile);244 }245 }246 if(tfwReader == null) throw new IOException("No Worldfile found.");247 248 if(refSys == null){249 // if no crs is delivered try to read projection file:250 refSys = readPrjFile(file);251 if(refSys == null) throw new IOException("No projection file found.");252 }253 254 BufferedImage img = ImageIO.read(file);255 256 // create Envelope257 double width = (double) (img.getWidth() * tfwReader.getXPixelSize());258 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));259 double lowerLeft_x = (double) tfwReader.getXULC();260 double lowerLeft_y = (double) tfwReader.getYULC() - height;261 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));262 263 coverage = createGridCoverage(img, bbox, refSys);264 }265 else{266 throw new IOException("Image type not supported. Supported formats are: \n" +267 Arrays.toString(SUPPORTEDIMAGETYPES.values()));268 }269 270 return coverage;271 }272 273 /**274 * Searches for a projection file (.prj) with the same name of 'file'275 * tries to parse it.276 *277 *278 * @param file image file, not the real world file (will be searched)279 * @return280 * @throws IOException281 */282 public static CoordinateReferenceSystem readPrjFile(File file) throws IOException283 {284 285 CoordinateReferenceSystem refSys = null;286 287 String prjFilename = null;288 int dotPos = file.getAbsolutePath().lastIndexOf(".");289 prjFilename = file.getAbsolutePath().substring(0, dotPos) + ".prj";290 291 File prjFile = new File(prjFilename);292 if(!prjFile.exists()) throw new IOException("No projection file found (.prj) for image '" + file.getName() + "'");293 logger.debug("Loading .prj file: " + prjFile.getAbsolutePath());294 295 StringBuilder sb = new StringBuilder();296 String content = null;297 BufferedReader br = new BufferedReader(new FileReader(prjFile));298 while((content = br.readLine()) != null)299 {300 sb.append(content);301 }302 303 try {304 refSys = CRS.parseWKT(sb.toString().trim());305 } catch (FactoryException e) {306 throw new IOException("Unable to parse prj-file: '" + prjFile.getName() + "'");307 }308 309 return refSys;310 311 }312 313 314 /**315 * Method for external use.316 *317 * @param img318 * @param bbox319 * @param crs320 * @return321 */322 public static GridCoverage2D createGridCoverage(BufferedImage img, Envelope2D bbox, CoordinateReferenceSystem crs)323 {324 bbox.setCoordinateReferenceSystem(crs);325 return new GridCoverageFactory().create("", img, bbox);326 }327 328 /**329 * Method for reading a GeoTIFF file.330 *331 * @param file332 * @param refSys if delivered, the coverage will be forced to use this crs333 * @return334 * @throws IOException335 * @throws FactoryException336 */337 public static GridCoverage2D readGeoTiff(File file, CoordinateReferenceSystem refSys) throws IOException, FactoryException338 {339 GridCoverage2D coverage = null;340 Hints hints = new Hints();341 if(refSys != null)342 {343 hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, refSys);344 345 }346 // dont't use the EPSG-Factory because of wrong behaviour347 hints.put(Hints.CRS_AUTHORITY_FACTORY, CRS.getAuthorityFactory(true));348 349 GeoTiffReader reader = new GeoTiffReader(file, hints);350 351 coverage = (GridCoverage2D) reader.read(null);352 353 return coverage;354 }355 356 357 /**358 * Loads CRS data from an EPSG database and creates descrptions for each one.359 *360 * @param pluginProps361 * @throws Exception362 */363 public static void loadCRSData(Properties pluginProps)364 {365 String defaultcrsString = pluginProps.getProperty("default_crs_srid");366 367 crsDescriptions = new Vector<String>();368 Set<String> supportedCodes = CRS.getSupportedCodes("EPSG");369 CRSAuthorityFactory fac = CRS.getAuthorityFactory(false);370 371 for (Iterator iterator = supportedCodes.iterator(); iterator.hasNext();) {372 String string = (String) iterator.next();373 try {374 InternationalString desc = fac.getDescriptionText("EPSG:" + string);375 376 String description = desc.toString() + " [-EPSG:" + string + "-]";377 378 crsDescriptions.add(description);379 380 if(defaultcrsString != null && defaultcrsString.equalsIgnoreCase("EPSG:" + string)){381 boolean isEastingFirst = Boolean.valueOf(pluginProps.getProperty("default_crs_eastingfirst"));382 defaultSourceCRS = CRS.decode("EPSG:" + string, isEastingFirst);383 defaultSourceCRSDescription = description;384 }385 } catch (NoSuchAuthorityCodeException e) {386 if(!string.equalsIgnoreCase("WGS84(DD)")){387 logger.error("Error while loading EPSG data: " + e.getMessage());388 }389 } catch (FactoryException e) {390 logger.error("Error while loading EPSG data: " + e.getMessage());391 }392 }393 }394 49 private static final Logger logger = Logger.getLogger(PluginOperations.class); 50 51 // contains descriptions of all available CRS 52 static Vector<String> crsDescriptions; 53 54 // the standard native CRS of user images 55 static CoordinateReferenceSystem defaultSourceCRS; 56 // description of 'defaultSourceCRS' 57 static String defaultSourceCRSDescription; 58 59 60 61 public static enum SUPPORTEDIMAGETYPES { 62 tiff, tif, jpg, jpeg, bmp, png 63 } 64 65 public static enum POSTFIXES_WORLDFILE { 66 wld, jgw, jpgw, pgw, pngw, tfw, tifw, bpw, bmpw, 67 }; 68 69 /** 70 * Reprojects a GridCoverage to a given CRS. 71 * 72 * @param coverage 73 * @param targetCrs 74 * @return destination 75 * @throws FactoryException 76 * @throws NoSuchAuthorityCodeException 77 */ 78 public static GridCoverage2D reprojectCoverage(GridCoverage2D coverage, 79 CoordinateReferenceSystem targetCrs) throws NoSuchAuthorityCodeException, FactoryException { 80 81 // TODO: add category for NO_DATA values in coverage (transparency in 82 // image) 83 84 GridCoverage2D destination = null; 85 86 DefaultProcessor processor = new DefaultProcessor(null); 87 ParameterValueGroup resampleParams = processor.getOperation("Resample") 88 .getParameters(); 89 90 // set parameters 91 resampleParams.parameter("Source").setValue(coverage); 92 resampleParams.parameter("CoordinateReferenceSystem").setValue( 93 targetCrs); 94 95 // resample coverage with given parameters 96 destination = (GridCoverage2D) processor.doOperation(resampleParams); 97 98 return destination; 99 } 100 101 /** 102 * Creates a org.geotools.coverage.grid.GridCoverage2D from a given file. 103 * 104 * @param file 105 * @return 106 * @throws IOException 107 * @throws Exception 108 */ 109 public static GridCoverage2D createGridFromFile(File file, CoordinateReferenceSystem refSys) throws IOException{ 110 111 GridCoverage2D coverage = null; 112 113 if (!file.exists()) throw new FileNotFoundException("File not found."); 114 115 String extension = null; 116 String fileNameWithoutExt = null; 117 int dotPos = file.getAbsolutePath().lastIndexOf("."); 118 extension = file.getAbsolutePath().substring(dotPos); 119 fileNameWithoutExt = file.getAbsolutePath().substring(0, dotPos); 120 121 /*------- switch for file type -----------*/ 122 if (extension.equalsIgnoreCase(".tif") 123 || extension.equalsIgnoreCase(".tiff")) 124 { 125 126 // try to read GeoTIFF: 127 try{ 128 coverage = readGeoTiff(file, refSys); 129 return coverage; 130 }catch (DataSourceException dse) { 131 if(!dse.getMessage().contains("Coordinate Reference System is not available")){ 132 dse.printStackTrace(); 133 } 134 } catch (FactoryException facte) { 135 logger.fatal("Error while reading from GeoTIFF:", facte); 136 throw new IOException(facte); 137 } 138 139 // file is no GeoTiff, searching for Worldfile and projection file: 140 String[] postfixes = {"wld", "tfw", "tifw"}; 141 // try to read Worldfile: 142 WorldFileReader tfwReader = null; 143 for (int i = 0; i < postfixes.length; i++) { 144 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 145 if(prjFile.exists()){ 146 tfwReader = new WorldFileReader(prjFile); 147 } 148 } 149 if(tfwReader == null){ 150 throw new IOException("No Worldfile found."); 151 } 152 153 if(refSys == null){ 154 // if no crs is delivered try to read projection file: 155 refSys = readPrjFile(file); 156 if(refSys == null) throw new IOException("No projection file found."); 157 } 158 159 BufferedImage img = ImageIO.read(file); 160 161 // create Envelope 162 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 163 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 164 double lowerLeft_x = (double) tfwReader.getXULC(); 165 double lowerLeft_y = (double) tfwReader.getYULC() - height; 166 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 167 168 coverage = createGridCoverage(img, bbox, refSys); 169 170 } 171 // 172 else if (extension.equalsIgnoreCase(".jpg") 173 || extension.equalsIgnoreCase(".jpeg")) 174 { 175 String[] postfixes = {"wld", "jgw", "jpgw"}; 176 // try to read Worldfile: 177 WorldFileReader tfwReader = null; 178 for (int i = 0; i < postfixes.length; i++) { 179 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 180 if(prjFile.exists()){ 181 tfwReader = new WorldFileReader(prjFile); 182 } 183 } 184 if(tfwReader == null) throw new IOException("No Worldfile found."); 185 186 if(refSys == null){ 187 // if no crs is delivered try to read projection file: 188 refSys = readPrjFile(file); 189 if(refSys == null) throw new IOException("No projection file found."); 190 } 191 192 BufferedImage img = ImageIO.read(file); 193 194 // create Envelope 195 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 196 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 197 double lowerLeft_x = (double) tfwReader.getXULC(); 198 double lowerLeft_y = (double) tfwReader.getYULC() - height; 199 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 200 201 coverage = createGridCoverage(img, bbox, refSys); 202 203 } 204 else if(extension.equalsIgnoreCase(".bmp")) 205 { 206 String[] postfixes = {"wld", "bmpw", "bpw"}; 207 // try to read Worldfile: 208 WorldFileReader tfwReader = null; 209 for (int i = 0; i < postfixes.length; i++) { 210 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 211 if(prjFile.exists()){ 212 tfwReader = new WorldFileReader(prjFile); 213 } 214 } 215 if(tfwReader == null) throw new IOException("No Worldfile found."); 216 217 if(refSys == null){ 218 // if no crs is delivered try to read projection file: 219 refSys = readPrjFile(file); 220 if(refSys == null) throw new IOException("No projection file found."); 221 } 222 223 BufferedImage img = ImageIO.read(file); 224 225 // create Envelope 226 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 227 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 228 double lowerLeft_x = (double) tfwReader.getXULC(); 229 double lowerLeft_y = (double) tfwReader.getYULC() - height; 230 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 231 232 coverage = createGridCoverage(img, bbox, refSys); 233 } 234 else if(extension.equalsIgnoreCase(".png")) 235 { 236 237 String[] postfixes = {"wld", "pgw", "pngw"}; 238 // try to read Worldfile: 239 WorldFileReader tfwReader = null; 240 for (int i = 0; i < postfixes.length; i++) { 241 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 242 if(prjFile.exists()){ 243 tfwReader = new WorldFileReader(prjFile); 244 } 245 } 246 if(tfwReader == null) throw new IOException("No Worldfile found."); 247 248 if(refSys == null){ 249 // if no crs is delivered try to read projection file: 250 refSys = readPrjFile(file); 251 if(refSys == null) throw new IOException("No projection file found."); 252 } 253 254 BufferedImage img = ImageIO.read(file); 255 256 // create Envelope 257 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 258 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 259 double lowerLeft_x = (double) tfwReader.getXULC(); 260 double lowerLeft_y = (double) tfwReader.getYULC() - height; 261 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 262 263 coverage = createGridCoverage(img, bbox, refSys); 264 } 265 else{ 266 throw new IOException("Image type not supported. Supported formats are: \n" + 267 Arrays.toString(SUPPORTEDIMAGETYPES.values())); 268 } 269 270 return coverage; 271 } 272 273 /** 274 * Searches for a projection file (.prj) with the same name of 'file' 275 * tries to parse it. 276 * 277 * 278 * @param file image file, not the real world file (will be searched) 279 * @return 280 * @throws IOException 281 */ 282 public static CoordinateReferenceSystem readPrjFile(File file) throws IOException 283 { 284 285 CoordinateReferenceSystem refSys = null; 286 287 String prjFilename = null; 288 int dotPos = file.getAbsolutePath().lastIndexOf("."); 289 prjFilename = file.getAbsolutePath().substring(0, dotPos) + ".prj"; 290 291 File prjFile = new File(prjFilename); 292 if(!prjFile.exists()) throw new IOException("No projection file found (.prj) for image '" + file.getName() + "'"); 293 logger.debug("Loading .prj file: " + prjFile.getAbsolutePath()); 294 295 StringBuilder sb = new StringBuilder(); 296 String content = null; 297 BufferedReader br = new BufferedReader(new FileReader(prjFile)); 298 while((content = br.readLine()) != null) 299 { 300 sb.append(content); 301 } 302 303 try { 304 refSys = CRS.parseWKT(sb.toString().trim()); 305 } catch (FactoryException e) { 306 throw new IOException("Unable to parse prj-file: '" + prjFile.getName() + "'"); 307 } 308 309 return refSys; 310 311 } 312 313 314 /** 315 * Method for external use. 316 * 317 * @param img 318 * @param bbox 319 * @param crs 320 * @return 321 */ 322 public static GridCoverage2D createGridCoverage(BufferedImage img, Envelope2D bbox, CoordinateReferenceSystem crs) 323 { 324 bbox.setCoordinateReferenceSystem(crs); 325 return new GridCoverageFactory().create("", img, bbox); 326 } 327 328 /** 329 * Method for reading a GeoTIFF file. 330 * 331 * @param file 332 * @param refSys if delivered, the coverage will be forced to use this crs 333 * @return 334 * @throws IOException 335 * @throws FactoryException 336 */ 337 public static GridCoverage2D readGeoTiff(File file, CoordinateReferenceSystem refSys) throws IOException, FactoryException 338 { 339 GridCoverage2D coverage = null; 340 Hints hints = new Hints(); 341 if(refSys != null) 342 { 343 hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, refSys); 344 345 } 346 // dont't use the EPSG-Factory because of wrong behaviour 347 hints.put(Hints.CRS_AUTHORITY_FACTORY, CRS.getAuthorityFactory(true)); 348 349 GeoTiffReader reader = new GeoTiffReader(file, hints); 350 351 coverage = (GridCoverage2D) reader.read(null); 352 353 return coverage; 354 } 355 356 357 /** 358 * Loads CRS data from an EPSG database and creates descrptions for each one. 359 * 360 * @param pluginProps 361 * @throws Exception 362 */ 363 public static void loadCRSData(Properties pluginProps) 364 { 365 String defaultcrsString = pluginProps.getProperty("default_crs_srid"); 366 367 crsDescriptions = new Vector<String>(); 368 Set<String> supportedCodes = CRS.getSupportedCodes("EPSG"); 369 CRSAuthorityFactory fac = CRS.getAuthorityFactory(false); 370 371 for (Iterator iterator = supportedCodes.iterator(); iterator.hasNext();) { 372 String string = (String) iterator.next(); 373 try { 374 InternationalString desc = fac.getDescriptionText("EPSG:" + string); 375 376 String description = desc.toString() + " [-EPSG:" + string + "-]"; 377 378 crsDescriptions.add(description); 379 380 if(defaultcrsString != null && defaultcrsString.equalsIgnoreCase("EPSG:" + string)){ 381 boolean isEastingFirst = Boolean.valueOf(pluginProps.getProperty("default_crs_eastingfirst")); 382 defaultSourceCRS = CRS.decode("EPSG:" + string, isEastingFirst); 383 defaultSourceCRSDescription = description; 384 } 385 } catch (NoSuchAuthorityCodeException e) { 386 if(!string.equalsIgnoreCase("WGS84(DD)")){ 387 logger.error("Error while loading EPSG data: " + e.getMessage()); 388 } 389 } catch (FactoryException e) { 390 logger.error("Error while loading EPSG data: " + e.getMessage()); 391 } 392 } 393 } 394 395 395 }
Note:
See TracChangeset
for help on using the changeset viewer.
