Statistics
| Revision:

root / trunk / libraries / libCresques / src / org / cresques / io / GeoRasterFile.java @ 13130

History | View | Annotate | Download (27 KB)

1
/*
2
 * Cresques Mapping Suite. Graphic Library for constructing mapping applications.
3
 *
4
 * Copyright (C) 2004-5.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
19
 *
20
 * For more information, contact:
21
 *
22
 * cresques@gmail.com
23
 */
24
package org.cresques.io;
25

    
26
import java.awt.Component;
27
import java.awt.Dimension;
28
import java.awt.Image;
29
import java.awt.geom.AffineTransform;
30
import java.awt.geom.Point2D;
31
import java.awt.image.DataBuffer;
32
import java.io.BufferedReader;
33
import java.io.File;
34
import java.io.FileInputStream;
35
import java.io.FileNotFoundException;
36
import java.io.FileReader;
37
import java.io.FileWriter;
38
import java.io.IOException;
39
import java.lang.reflect.Constructor;
40
import java.lang.reflect.InvocationTargetException;
41
import java.util.TreeMap;
42

    
43
import org.cresques.cts.ICoordTrans;
44
import org.cresques.cts.IProjection;
45
import org.cresques.filter.PixelFilter;
46
import org.cresques.filter.SimplePixelFilter;
47
import org.cresques.io.data.Metadata;
48
import org.cresques.io.data.RasterMetaFileTags;
49
import org.cresques.px.Extent;
50
import org.cresques.px.IObjList;
51
import org.cresques.px.PxContour;
52
import org.cresques.px.PxObjList;
53
import org.kxml2.io.KXmlParser;
54
import org.xmlpull.v1.XmlPullParserException;
55

    
56
/**
57
 * Manejador de ficheros raster georeferenciados.
58
 *
59
 * Esta clase abstracta es el ancestro de todas las clases que proporcionan
60
 * soporte para ficheros raster georeferenciados.<br>
61
 * Actua tambien como una 'Fabrica', ocultando al cliente la manera en que
62
 * se ha implementado ese manejo. Una clase nueva que soportara un nuevo
63
 * tipo de raster tendr?a que registrar su extensi?n o extensiones usando
64
 * el m?todo @see registerExtension.<br>
65
 * @author "Luis W. Sevilla" <sevilla_lui@gva.es>*
66
 */
67

    
68
public abstract class GeoRasterFile extends GeoFile {
69

    
70
        /**
71
         * Flag que representa a la banda del Rojo
72
         */
73
        public static final int         RED_BAND        = 0x01;
74

    
75
        /**
76
         * Flag que representa a la banda del Verde
77
         */
78
        public static final int         GREEN_BAND        = 0x02;
79

    
80
        /**
81
         * Flag que representa a la banda del Azul
82
         */
83
        public static final int         BLUE_BAND        = 0x04;
84
        private static TreeMap                 supportedExtensions = null;
85
        protected Component                 updatable = null;
86
        protected boolean                         doTransparency = false;
87
        private boolean                                verifySize = false;
88
        /**
89
         * Par?metros de transformaci?n del fichero .rmf. Esta ser? distinta
90
         * de la identidad si la funci?n rmfExists() devuelve true.
91
         */
92
        protected AffineTransform        rmfTransform = new AffineTransform();
93

    
94
        /**
95
         * Filtro para raster.
96
         * Permite eliminar la franja inutil alrededor de un raster girado o de
97
         * un mosaico de borde irregular.
98
         *
99
         * Funciona bien solo con raster en tonos de gris, porque se basa que
100
         * el valor del pixel no supere un determinado valor 'umbral' que se
101
         * le pasa al constructor.
102
         *
103
         * Desarrollado para 'limpiar' los bordes de los mosaicos del SIG
104
         * Oleicola. Para ese caso los par?metros del constructo son:
105
         * PixelFilter(0x10ffff00, 0xff000000, 0xf0f0f0);
106
         */
107
        protected PixelFilter                 tFilter = null;
108

    
109
        /**
110
         * Asignaci?n de banda del Rojo a una banda de la imagen
111
         */
112
        protected int                                 rBandNr = 1;
113

    
114
        /**
115
         * Asignaci?n de banda del Verde a una banda de la imagen
116
         */
117
        protected int                                 gBandNr = 1;
118

    
119
        /**
120
         * Asignaci?n de banda del Azul a una banda de la imagen
121
         */
122
        protected int                                 bBandNr = 1;
123

    
124
        /**
125
         * N?mero de bandas de la imagen
126
         */
127
        protected int                                 bandCount = 1;
128
        private int                                 dataType = DataBuffer.TYPE_BYTE;
129
        /**
130
         * Par?metros de transformaci?n del fichero .rmf. Estas variables tendr?n valores distinto
131
         * de 0 si la funci?n rmfExists() devuelve true.
132
         */
133
        //protected double originX = 0D, originY = 0D, w = 0D, h = 0D;
134
        //protected double pixelSizeX = 0D, pixelSizeY = 0D;
135
        protected double imageWidth = 0D, imageHeight = 0D;
136
        //protected double shearX = 0D, shearY = 0D;
137

    
138
        static {
139
                supportedExtensions = new TreeMap();
140
                supportedExtensions.put("ecw",  EcwFile.class);
141
                supportedExtensions.put("jp2",  EcwFile.class);
142

    
143
                supportedExtensions.put("sid",  MrSidFile.class);
144

    
145
                supportedExtensions.put("bmp", GdalFile.class);
146
                supportedExtensions.put("gif", GdalFile.class);
147
                supportedExtensions.put("img", GdalFile.class);
148
                supportedExtensions.put("tif", GdalFile.class);
149
                supportedExtensions.put("tiff", GdalFile.class);
150
                supportedExtensions.put("jpg", GdalFile.class);
151
                supportedExtensions.put("png", GdalFile.class);
152
                //supportedExtensions.put("jpg",  TifGeoRefFile.class);
153
                //supportedExtensions.put("png",  TifGeoRefFile.class);
154
                //supportedExtensions.put("dat",  GdalFile.class);
155
        }
156

    
157
        /**
158
         * Factoria para abrir distintos tipos de raster.
159
         *
160
         * @param proj Proyecci?n en la que est? el raster.
161
         * @param fName Nombre del fichero.
162
         * @return GeoRasterFile, o null si hay problemas.
163
         */
164
        public static GeoRasterFile openFile(IProjection proj, String fName) {
165
                String ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
166
                GeoRasterFile grf = null;
167
                // TODO NotSupportedExtensionException
168
                if (!supportedExtensions.containsKey(ext)) return grf;
169
                /**/
170
                Class clase = (Class) supportedExtensions.get(ext);
171
                Class [] args = {IProjection.class, String.class};
172
                try {
173
                        Constructor hazNuevo = clase.getConstructor(args);
174
                        Object [] args2 = {proj, fName};
175
                        grf = (GeoRasterFile) hazNuevo.newInstance(args2);
176
                        grf.setFileSize(new File(fName).length());
177
                } catch (SecurityException e) {
178
                        e.printStackTrace();
179
                } catch (NoSuchMethodException e) {
180
                        e.printStackTrace();
181
                } catch (IllegalArgumentException e) {
182
                        e.printStackTrace();
183
                } catch (InstantiationException e) {
184
                        e.printStackTrace();
185
                } catch (IllegalAccessException e) {
186
                        e.printStackTrace();
187
                } catch (InvocationTargetException e) {
188
                        e.printStackTrace();
189
                }
190

    
191
                return grf;
192
        }
193

    
194
        /**
195
         * Registra una clase que soporta una extensi?n raster.
196
         * @param ext extensi?n soportada.
197
         * @param clase clase que la soporta.
198
         */
199
        public static void registerExtension(String ext, Class clase) {
200
                ext = ext.toLowerCase();
201
                System.out.println("RASTER: extension '"+ext+"' supported.");
202
                supportedExtensions.put(ext, clase);
203
        }
204

    
205
        /**
206
         * Tipo de fichero soportado.
207
         * Devuelve true si el tipo de fichero (extension) est? soportado, si no
208
         * devuelve false.
209
         *
210
         * @param fName Fichero raster
211
         * @return  true si est? soportado, si no false.
212
                */
213
        public static boolean fileIsSupported(String fName) {
214
                String ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
215
                return supportedExtensions.containsKey(ext);
216
        }
217

    
218
        /**
219
         * Constructor
220
         * @param proj        Proyecci?n
221
         * @param name        Nombre del fichero de imagen.
222
         */
223
        public GeoRasterFile(IProjection proj, String name) {
224
                super(proj, name);
225
        }
226

    
227
        /**
228
         * Carga un fichero raster. Puede usarse para calcular el extent e instanciar
229
         * un objeto de este tipo.
230
         */
231
        abstract public GeoFile load();
232

    
233
        /**
234
         * Cierra el fichero y libera los recursos.
235
         */
236
        abstract public void close();
237

    
238
        /**
239
         * Obtiene la codificaci?n del fichero XML
240
         * @param file Nombre del fichero XML
241
         * @return Codificaci?n
242
         */
243
        private String readFileEncoding(String file){
244
                FileReader fr;
245
                String encoding = null;
246
                try
247
                        {
248
                        fr = new FileReader(file);
249
                                BufferedReader br = new BufferedReader(fr);
250
                                char[] buffer = new char[100];
251
                                br.read(buffer);
252
                                StringBuffer st = new StringBuffer(new String(buffer));
253
                                String searchText = "encoding=\"";
254
                                int index = st.indexOf(searchText);
255
                                if (index>-1) {
256
                                        st.delete(0, index+searchText.length());
257
                                        encoding = st.substring(0, st.indexOf("\""));
258
                                }
259
                                fr.close();
260
                        } catch(FileNotFoundException ex)        {
261
                                ex.printStackTrace();
262
                        } catch (IOException e) {
263
                        e.printStackTrace();
264
                }
265
                        return encoding;
266
        }
267

    
268
        private double[] parserExtent(KXmlParser parser) throws XmlPullParserException, IOException {
269
                double originX = 0D, originY = 0D, w = 0D, h = 0D;
270
                double pixelSizeX = 0D, pixelSizeY = 0D;
271
                double shearX = 0D, shearY = 0D;
272

    
273
                boolean end = false;
274
                        int tag = parser.next();
275
                        while (!end) {
276
                                switch(tag) {
277
                                                case KXmlParser.START_TAG:
278
                                                        if(parser.getName() != null){
279
                                                if (parser.getName().equals(RasterMetaFileTags.POSX)){
280
                                                        originX = Double.parseDouble(parser.nextText());
281
                                                }else if (parser.getName().equals(RasterMetaFileTags.POSY)){
282
                                                        originY = Double.parseDouble(parser.nextText());
283
                                                }else if (parser.getName().equals(RasterMetaFileTags.PX_SIZE_X)){
284
                                                        pixelSizeX = Double.parseDouble(parser.nextText());
285
                                                }else if (parser.getName().equals(RasterMetaFileTags.PX_SIZE_Y)){
286
                                                        pixelSizeY = Double.parseDouble(parser.nextText());
287
                                                }else if (parser.getName().equals(RasterMetaFileTags.ROTX)){
288
                                                        shearX = Double.parseDouble(parser.nextText());
289
                                                }else if (parser.getName().equals(RasterMetaFileTags.ROTY)){
290
                                                        shearY = Double.parseDouble(parser.nextText());
291
                                                }else if (parser.getName().equals(RasterMetaFileTags.WIDTH)){
292
                                                        w = Double.parseDouble(parser.nextText());
293
                                                }else if (parser.getName().equals(RasterMetaFileTags.HEIGHT)){
294
                                                        h = Double.parseDouble(parser.nextText());
295
                                                }
296
                                        }
297
                                        break;
298
                                                 case KXmlParser.END_TAG:
299
                                                         if (parser.getName().equals(RasterMetaFileTags.BBOX))
300
                                                                 end = true;
301
                                                        break;
302
                                                case KXmlParser.TEXT:
303
                                                        break;
304
                                }
305
                                tag = parser.next();
306
                        }
307

    
308
                        double[] values = {originX, originY, w, h, pixelSizeX, pixelSizeY, shearX, shearY};
309
                return values;
310
        }
311

    
312
        /**
313
         * Obtiene la informaci?n de georreferenciaci?n asociada a la imagen en un fichero .rmf. Esta
314
         * georreferenciaci?n tiene la caracteristica de que tiene prioridad sobre la de la imagen.
315
         * Es almacenada en la clase GeoFile en la variable virtualExtent.
316
         * @param file Fichero de metadatos .rmf
317
         */
318
        protected void readGeoInfo(String file){
319
                String rmf = file.substring(0, file.lastIndexOf(".") + 1) + "rmf";
320
                File rmfFile = new File(rmf);
321
                if(!rmfFile.exists())
322
                        return;
323

    
324
                boolean georefOk = false;
325

    
326
                FileReader fr = null;
327
                try {
328
                        fr = new FileReader(rmf);
329
                        KXmlParser parser = new KXmlParser();
330
                        parser.setInput(new FileInputStream(rmf), readFileEncoding(rmf));
331
                        int tag = parser.nextTag();
332
                        if ( parser.getEventType() != KXmlParser.END_DOCUMENT ){
333
                                parser.require(KXmlParser.START_TAG, null, RasterMetaFileTags.MAIN_TAG);
334
                                while(tag != KXmlParser.END_DOCUMENT) {
335
                                        switch(tag) {
336
                                                case KXmlParser.START_TAG:
337
                                                        if (parser.getName().equals(RasterMetaFileTags.LAYER)) {
338
                                                                parser.next();
339
                                                                boolean geoRefEnd = false;
340
                                                                while (!geoRefEnd){
341
                                                                        if(parser.getName() != null){
342
                                                                                if (parser.getName().equals(RasterMetaFileTags.PROJ)){
343
                                                                                        //System.out.println("PROJ:"+parser.nextText());
344
                                                                                } else if (parser.getName().equals(RasterMetaFileTags.BBOX)){
345
                                                                                        double[] values = parserExtent(parser);
346
                                                                                        rmfTransform = new AffineTransform(        values[4], values[7],
347
                                                                                                                                                                                                                         values[6], values[5],
348
                                                                                                                                                                         values[0], values[1]);
349
                                                                                        georefOk = true;
350
                                                                                } else if (parser.getName().equals(RasterMetaFileTags.DIM)){
351
                                                                                        boolean DimEnd = false;
352
                                                                                        while (!DimEnd){
353
                                                                                                parser.next();
354
                                                                                                if(parser.getName() != null){
355
                                                                                                        if (parser.getName().equals(RasterMetaFileTags.PX_WIDTH)){
356
                                                                                                                imageWidth = Double.parseDouble(parser.nextText());
357
                                                                                                        }else if (parser.getName().equals(RasterMetaFileTags.PX_HEIGHT)){
358
                                                                                                                imageHeight = Double.parseDouble(parser.nextText());
359
                                                                                                                DimEnd = true;
360
                                                                                                        }
361
                                                                                                }
362
                                                                                        }
363
                                                                                        geoRefEnd = true;
364
                                                                                }
365
                                                                        }
366
                                                                        parser.next();
367
                                                                }
368
                                                        }
369
                                                        break;
370
                                                case KXmlParser.END_TAG:
371
                                                        break;
372
                                                case KXmlParser.TEXT:
373
                                                        break;
374
                                        }
375
                                        tag = parser.next();
376
                                }
377
                                parser.require(KXmlParser.END_DOCUMENT, null, null);
378
                        }
379

    
380
                        if(georefOk){
381
                                rmfExists = true;
382
                                setExtentTransform(        rmfTransform.getTranslateX(), rmfTransform.getTranslateY(),
383
                                                                        rmfTransform.getScaleX(), rmfTransform.getScaleY());
384
                                createExtentsFromRMF(        rmfTransform.getTranslateX(), rmfTransform.getTranslateY(),
385
                                                                                rmfTransform.getScaleX(), rmfTransform.getScaleY(),
386
                                                                                imageWidth, imageHeight,
387
                                                                                rmfTransform.getShearX(), rmfTransform.getShearY());
388
                        }
389

    
390
                } catch (FileNotFoundException fnfEx) {
391
                } catch (XmlPullParserException xmlEx) {
392
                        xmlEx.printStackTrace();
393
                } catch (IOException e) {
394
                }
395
                try{
396
                        if(fr != null)
397
                                fr.close();
398
                }catch(IOException ioEx){
399
                        //No est? abierto el fichero por lo que no hacemos nada
400
                }
401
        }
402

    
403
        /**
404
         * Asigna una transformaci?n al raster para que se tenga en cuenta en la asignaci?n del setView.
405
         * Esta asignaci?n recalcula el extent, el requestExtent y asigna el AffineTransform que se
406
         * usar? para la transformaci?n. Esta transformaci?n ser? considerada como si la imagen tuviera
407
         * asociado un rmf.
408
         * @param t Transformaci?n af?n a aplicar
409
         */
410
        public void setAffineTransform(AffineTransform t){
411
                rmfExists = true;
412
                rmfTransform = (AffineTransform)t.clone();
413
                setExtentTransform(t.getTranslateX(), t.getTranslateY(), t.getScaleX(), t.getScaleY());
414
                createExtentsFromRMF(        t.getTranslateX(), t.getTranslateY(), t.getScaleX(), t.getScaleY(),
415
                                                                this.getWidth(), this.getHeight(),
416
                                                                t.getShearX(), t.getShearY());
417
        }
418

    
419
        /**
420
         * Asigna una transformaci?n al raster para que se tenga en cuenta en la asignaci?n del setView.
421
         * Esta asignaci?n recalcula el extent, el requestExtent y asigna el AffineTransform que se
422
         * usar? para la transformaci?n. Esta transformaci?n ser? considerada como si la imagen tuviera
423
         * asociado un rmf.
424
         * @param originX Coordenada X de origen del raster
425
         * @param originY Coordenada Y de origen del raster
426
         * @param pixelSizeX Tama?o de pixel en X
427
         * @param pixelSizeY Tama?o de pixel en Y
428
         * @param imageWidth Ancho del raster en pixels
429
         * @param imageHeight Alto del raster en pixels
430
         * @param shearX Shearing en X
431
         * @param shearY Shearing en Y
432
         */
433
        public void setAffineTransform(        double originX, double originY, double pixelSizeX,
434
                                                                                double pixelSizeY, double shearX, double shearY){
435
                rmfExists = true;
436
                rmfTransform.setToTranslation(originX, originY);
437
                rmfTransform.shear(shearX, shearY);
438
                rmfTransform.scale(pixelSizeX, pixelSizeY);
439
                setExtentTransform(originX, originY, pixelSizeX, pixelSizeY);
440
                createExtentsFromRMF(        originX, originY, pixelSizeX, pixelSizeY,
441
                                                                imageWidth, imageHeight, shearX, shearY);
442
        }
443

    
444
        /**
445
         * Obtiene la matriz de transformaci?n que se aplica sobre la visualizaci?n
446
         * del raster.
447
         * @return Matriz de transformaci?n.
448
         */
449
        public AffineTransform getAffineTransform(){
450
                return rmfTransform;
451
        }
452

    
453
        /**
454
         * Elimina la matriz de transformaci?n asociada al raster y que se tiene en cuenta para
455
         * el setView. Este reseteo tendr? en cuenta que si el raster tiene asociado un rmf
456
         * esta transformaci?n no ser? eliminada sino que se asignar? la correspondiente al rmf
457
         * existente.
458
         * @return devuelve true si tiene fichero rmf asociado y false si no lo tiene.
459
         */
460
        public boolean resetAffineTransform(){
461
                rmfExists = false;
462
                rmfTransform.setToIdentity();
463

    
464
                //Crea los extent iniciales
465
                load();
466

    
467
                //Lee y carga el rmf si existe
468
                readGeoInfo(this.getName());
469

    
470
                if(rmfExists)
471
                        return true;
472
                else
473
                        return false;
474
        }
475

    
476
        /**
477
         * <P>
478
         * Calcula el extent de la imagen a partir del fichero rmf con y sin rotaci?n. El extent con rotaci?n corresponde
479
         * a la variable extent que contiene el extent verdadero marcado por el fichero de georreferenciaci?n .rmf. El extent
480
         * sin rotaci?n requestExtent es utilizado para realizar la petici?n ya que la petici?n al driver no se puede
481
         * hacer con coordenadas rotadas.
482
         *
483
         * El calculo de la bounding box rotada lo hace con los valores de transformaci?n leidos desde el fichero .rmf.
484
         * </p>
485
         * <P>
486
         * Para el calculo de una esquina aplicamos la formula siguiente:<BR>
487
         * PtoX = originX + pixelSizeX * x + shearX * y;<BR>
488
         * PtoY = originY + shearY * x + pixelSizeY * y;<BR>
489
         * Aplicandolo a las cuatro esquinas sustituimos en cada una de ellas por.
490
         * </P>
491
         * <UL>
492
         * <LI>Esquina superior izquierda: x = 0; y = 0;</LI>
493
         * <LI>Esquina superior derecha: x = MaxX; y = 0;</LI>
494
         * <LI>Esquina inferior izquierda: x = 0; y = MaxY;</LI>
495
         * <LI>Esquina inferior derecha: x = MaxX; y = MaxY;</LI>
496
         * </UL>
497
         * <P>
498
         * quedandonos en los cuatro casos:
499
         * </P>
500
         * <UL>
501
         * <LI>Esquina superior izquierda: originX; originY;</LI>
502
         * <LI>Esquina superior derecha: PtoX = originX + pixelSizeX * x; PtoY = originY + shearY * x;</LI>
503
         * <LI>Esquina inferior izquierda:  PtoX = originX + shearX * y; PtoY = originY + pixelSizeY * y;</LI>
504
         * <LI>Esquina inferior derecha: PtoX = originX + pixelSizeX * x + shearX * y; PtoY = originY + shearY * x + pixelSizeY * y;</LI>
505
         * </UL>
506
         *
507
         * <P>
508
         * El calculo de la bounding box se realizar? de la misma forma pero anulando los parametros de shearing.
509
         * </P>
510
         *
511
         * @param originX Coordenada X de origen del raster
512
         * @param originY Coordenada Y de origen del raster
513
         * @param pixelSizeX Tama?o de pixel en X
514
         * @param pixelSizeY Tama?o de pixel en Y
515
         * @param imageWidth Ancho del raster en pixels
516
         * @param imageHeight Alto del raster en pixels
517
         * @param shearX Shearing en X
518
         * @param shearY Shearing en Y
519
         */
520
        private void createExtentsFromRMF(        double originX, double originY, double pixelSizeX, double pixelSizeY,
521
                                                                                double imageWidth, double imageHeight, double shearX, double shearY){
522

    
523
                Point2D p1 = new Point2D.Double(originX, originY);
524
                Point2D p2 = new Point2D.Double(originX + shearX * imageHeight, originY + pixelSizeY * imageHeight);
525
                Point2D p3 = new Point2D.Double(originX + pixelSizeX * imageWidth, originY + shearY * imageWidth);
526
                Point2D p4 = new Point2D.Double(originX + pixelSizeX * imageWidth + shearX * imageHeight, originY + pixelSizeY * imageHeight + shearY * imageWidth);
527

    
528
                double minX = Math.min(Math.min(p1.getX(), p2.getX()), Math.min(p3.getX(), p4.getX()));
529
                double minY = Math.min(Math.min(p1.getY(), p2.getY()), Math.min(p3.getY(), p4.getY()));
530
                double maxX = Math.max(Math.max(p1.getX(), p2.getX()), Math.max(p3.getX(), p4.getX()));
531
                double maxY = Math.max(Math.max(p1.getY(), p2.getY()), Math.max(p3.getY(), p4.getY()));
532
                extent = new Extent(minX, minY, maxX, maxY);
533
                requestExtent = new Extent(originX, originY, originX + (pixelSizeX * imageWidth), originY + (pixelSizeY * imageHeight));
534
        }
535

    
536
        /**
537
         * Calcula la transformaci?n que se produce sobre la vista cuando la imagen tiene un fichero .rmf
538
         * asociado. Esta transformaci?n tiene diferencias entre los distintos formatos por lo que debe calcularla
539
         * el driver correspondiente.
540
         * @param originX Origen de la imagen en la coordenada X
541
         * @param originY Origen de la imagen en la coordenada Y
542
         */
543
        abstract public void setExtentTransform(double originX, double originY, double psX, double psY);
544

    
545
        public static PxContour getContour(String fName, String name, IProjection proj) {
546
                PxContour contour = null;
547
                return contour;
548
        }
549

    
550
        /**
551
         * Obtiene el ancho de la imagen
552
         * @return Ancho de la imagen
553
         */
554
        abstract public int getWidth();
555

    
556
        /**
557
         * Obtiene el ancho de la imagen
558
         * @return Ancho de la imagen
559
         */
560
        abstract public int getHeight();
561

    
562
        /**
563
         * Reproyecci?n.
564
         * @param rp        Coordenadas de la transformaci?n
565
         */
566
        abstract public void reProject(ICoordTrans rp);
567

    
568
        /**
569
         * Asigna un nuevo Extent
570
         * @param e        Extent
571
         */
572
        abstract public void setView(Extent e);
573

    
574
        /**
575
         * Obtiene el extent asignado
576
         * @return        Extent
577
         */
578
        abstract public Extent getView();
579

    
580
        public void setTransparency(boolean t) {
581
                doTransparency = t;
582
                tFilter = new PixelFilter(255);
583
        }
584

    
585
        /**
586
         * Asigna un valor de transparencia
587
         * @param t        Valor de transparencia
588
         */
589
        public void setTransparency(int t ) {
590
                doTransparency = true;
591
                tFilter = new SimplePixelFilter(255 - t);
592
        }
593

    
594
        public boolean getTransparency() { return doTransparency; }
595

    
596
        public void setAlpha(int alpha) {
597
                if (!doTransparency) setTransparency(255 - alpha);
598
                else tFilter.setAlpha(alpha);
599
        }
600
        public int getAlpha() {
601
                if (tFilter == null)
602
                        return 255;
603
                return tFilter.getAlpha();
604
        }
605

    
606
        public void setUpdatable(Component c) { updatable = c; }
607

    
608
        /**
609
         * Actualiza la imagen
610
         * @param width        ancho
611
         * @param height        alto
612
         * @param rp        Reproyecci?n
613
         * @return        img
614
         */
615
        abstract public Image updateImage(int width, int height, ICoordTrans rp);
616

    
617
        /**
618
         * Obtiene el valor del raster en la coordenada que se le pasa.
619
         * El valor ser? Double, Int, Byte, etc. dependiendo del tipo de
620
         * raster.
621
         * @param x        coordenada X
622
         * @param y coordenada Y
623
         * @return
624
         */
625
        abstract public Object getData(int x, int y, int band);
626

    
627
        /**
628
         * Actualiza la/s banda/s especificadas en la imagen.
629
         * @param width                ancho
630
         * @param height        alto
631
         * @param rp                reproyecci?n
632
         * @param img                imagen
633
         * @param flags                que bandas [ RED_BAND | GREEN_BAND | BLUE_BAND ]
634
         * @return                img
635
         * @throws SupersamplingNotSupportedException
636
         */
637
        abstract public Image updateImage(int width, int height, ICoordTrans rp, Image img, int origBand, int destBand)throws SupersamplingNotSupportedException;
638

    
639
        public int getBandCount() { return bandCount; }
640

    
641
        /**
642
         * Asocia un colorBand al rojo, verde o azul.
643
         * @param flag cual (o cuales) de las bandas.
644
         * @param nBand        que colorBand
645
         */
646

    
647
        public void setBand(int flag, int bandNr) {
648
                if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) rBandNr = bandNr;
649
                if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) gBandNr = bandNr;
650
                if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) bBandNr = bandNr;
651
        }
652

    
653
        /**
654
         * Devuelve el colorBand activo en la banda especificada.
655
         * @param flag banda.
656
         */
657

    
658
        public int getBand(int flag) {
659
                if (flag == GeoRasterFile.RED_BAND) return rBandNr;
660
                if (flag == GeoRasterFile.GREEN_BAND) return gBandNr;
661
                if (flag == GeoRasterFile.BLUE_BAND) return bBandNr;
662
                return -1;
663
        }
664

    
665
        /**
666
         * @return Returns the dataType.
667
         */
668
        public int getDataType() {
669
                return dataType;
670
        }
671

    
672
        /**
673
         * @param dataType The dataType to set.
674
         */
675
        public void setDataType(int dataType) {
676
                this.dataType = dataType;
677
        }
678

    
679
        public IObjList getObjects() {
680
                // TODO hay que a?adir el raster a la lista de objetos
681
                IObjList oList = new PxObjList(proj);
682
                return oList;
683
        }
684

    
685
        /**
686
         * Calcula los par?metros de un worl file a partir de las esquinas del raster.
687
         *    1. X pixel size A
688
         *    2. X rotation term D
689
         *    3. Y rotation term B
690
         *    4. Y pixel size E
691
         *    5. X coordinate of upper left corner C
692
         *    6. Y coordinate of upper left corner F
693
         * where the real-world coordinates x',y' can be calculated from
694
         * the image coordinates x,y with the equations
695
         *  x' = Ax + By + C and y' = Dx + Ey + F.
696
         *  The signs of the first 4 parameters depend on the orientation
697
         *  of the image. In the usual case where north is more or less
698
         *  at the top of the image, the X pixel size will be positive
699
         *  and the Y pixel size will be negative. For a south-up image,
700
         *  these signs would be reversed.
701
         *
702
         * You can calculate the World file parameters yourself based
703
         * on the corner coordinates. The X and Y pixel sizes can be
704
         *  determined simply by dividing the distance between two
705
         *  adjacent corners by the number of columns or rows in the image.
706
         *  The rotation terms are calculated with these equations:
707
         *
708
         *  # B = (A * number_of_columns + C - lower_right_x') / number_of_rows * -1
709
         *  # D = (E * number_of_rows + F - lower_right_y') / number_of_columns * -1
710
         *
711
         * @param corner (tl, tr, br, bl)
712
         * @return
713
         */
714
        public static double [] cornersToWorldFile(Point2D [] esq, Dimension size) {
715
                double a=0,b=0,c=0,d=0,e=0,f=0;
716
                double x1 = esq[0].getX(), y1 = esq[0].getY();
717
                double x2 = esq[1].getX(), y2 = esq[1].getY();
718
                double x3 = esq[2].getX(), y3 = esq[2].getY();
719
                double x4 = esq[3].getX(), y4 = esq[3].getY();
720
                // A: X-scale
721
                a = Math.abs( Math.sqrt( (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
722
                                        / size.getWidth());
723

    
724
                // E: negative Y-scale
725
                e =  - Math.abs(Math.sqrt((x1-x4)*(x1-x4)+
726
                                        (y1-y4)*(y1-y4))/size.getHeight());
727

    
728
                // C, F: upper-left coordinates
729
                c = x1;
730
                f = y1;
731

    
732
                // B & D: rotation parameters
733
                b = (a * size.getWidth() + c - x3 ) / size.getHeight() * -1;
734
                d = (e * size.getHeight() + f - y3 ) / size.getWidth() * -1;
735

    
736
                double [] wf = {a,d,b,e,c,f};
737
                return wf;
738
        }
739
                public static String printWF(String fName, Point2D [] esq, Dimension sz) {
740
                        double [] wf = GeoRasterFile.cornersToWorldFile(esq, sz);
741
                        System.out.println("wf para "+fName);
742
                        System.out.println(esq+"\n"+sz);
743
                        String wfData = "";
744
                        for (int i=0; i<6; i++)
745
                                wfData += wf[i]+"\n";
746
                System.out.println(wfData);
747
                return wfData;
748
                }
749

    
750
                public static void saveWF(String fName, String data) throws IOException {
751
                        FileWriter fw = new FileWriter(fName);
752
                        fw.write(data);
753
                        fw.flush();
754
                        fw.close();
755
                }
756

    
757
        /**
758
         * Cosulta si hay que verificar la relaci?n de aspecto de la imagen, es decir comprueba que el ancho/alto
759
         * pasados a updateImage coinciden con el ancho/alto solicitado en setView a la imagen
760
         * @return true si est? verificando la relaci?n de aspecto.
761
         */
762
        public boolean mustVerifySize() {
763
                return verifySize;
764
        }
765

    
766
        /**
767
         * Asigna el flag que dice si hay que verificar la relaci?n de aspecto de la imagen, es decir
768
         * comprueba que el ancho/alto pasados a updateImage coinciden con el ancho/alto solicitado
769
         * en setView a la imagen.
770
         * @return true si est? verificando la relaci?n de aspecto.
771
         */
772
        public void setMustVerifySize(boolean verifySize) {
773
                this.verifySize = verifySize;
774
        }
775

    
776
        abstract public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band);
777
        abstract public int getBlockSize();
778

    
779
        /**
780
         * Obtiene el objeto que contiene los metadatos. Este m?todo debe ser redefinido por los
781
         * drivers si necesitan devolver metadatos.
782
         * @return
783
         */
784
        public Metadata getMetadata(){
785
                return null;
786
        }
787

    
788
        /**
789
         * Asigna un extent temporal que puede coincidir con el de la vista. Esto es
790
         * util para cargar imagenes sin georreferenciar ya que podemos asignar el extent
791
         * que queramos para ajustarnos a una vista concreta
792
         * @param tempExtent The tempExtent to set.
793
         */
794
        public void setExtent(Extent ext) {
795
                this.extent = ext;
796
        }
797

    
798
        public boolean isGeoreferenced(){
799
                return true;
800
        }
801

    
802
        /**
803
         * M?todo que indica si existe un fichero .rmf asociado al GeoRasterFile.
804
         * @return
805
         */
806
        public boolean rmfExists(){
807
                return this.rmfExists;
808
        }
809

    
810
        /**
811
         * Obtiene los par?metros de la transformaci?n af?n que corresponde con los elementos de
812
         * un fichero tfw.
813
         * <UL>
814
         * <LI>[1]tama?o de pixel en X</LI>
815
         * <LI>[2]rotaci?n en X</LI>
816
         * <LI>[4]rotaci?n en Y</LI>
817
         * <LI>[5]tama?o de pixel en Y</LI>
818
         * <LI>[0]origen en X</LI>
819
         * <LI>[3]origen en Y</LI>
820
         * </UL>
821
         * Este m?todo debe ser reimplementado por el driver si tiene esta informaci?n. En principio
822
         * Gdal es capaz de proporcionarla de esta forma.
823
         * @return vector de double con los elementos de la transformaci?n af?n.
824
         */
825
        public double[] getTransform(){return null;}
826
}