Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1008 / libraries / libCq_CMS_praster / src / org / cresques / io / GeoRasterFile.java @ 12520

History | View | Annotate | Download (33.7 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.BandList;
48
import org.cresques.io.data.RasterBuf;
49
import org.cresques.io.data.RasterMetaFileTags;
50
import org.cresques.io.datastruct.Metadata;
51
import org.cresques.io.datastruct.Palette;
52
import org.cresques.io.exceptions.SupersamplingNotSupportedException;
53
import org.cresques.px.Extent;
54
import org.cresques.px.IObjList;
55
import org.cresques.px.PxContour;
56
import org.cresques.px.PxObjList;
57
import org.gvsig.i18n.Messages;
58
import org.kxml2.io.KXmlParser;
59
import org.xmlpull.v1.XmlPullParserException;
60

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

    
73
public abstract class GeoRasterFile extends GeoFile {
74
        
75
        /**
76
         * Flag que representa a la banda del Rojo
77
         */
78
        public static final int         RED_BAND        = 0x01;
79
        
80
        /**
81
         * Flag que representa a la banda del Verde
82
         */
83
        public static final int         GREEN_BAND        = 0x02;
84
        
85
        /**
86
         * Flag que representa a la banda del Azul
87
         */
88
        public static final int         BLUE_BAND        = 0x04;
89
        public static TreeMap                 supportedExtensions = null;
90
        protected Component                 updatable = null;
91
        protected boolean                         doTransparency = false;
92
        private boolean                                verifySize = false;
93
        /**
94
         * Par?metros de transformaci?n del fichero .rmf. Esta ser? distinta
95
         * de la identidad si la funci?n rmfExists() devuelve true.
96
         */
97
        protected AffineTransform        rmfTransform = new AffineTransform();
98
        
99
        /**
100
         * Esta variable estar? a true si el driver est? supersampleando en el ?ltimo dibujado.
101
         * Debe tenerse especial cuidado ya que est? consulta no es adecuada desde gvSIG ya que el
102
         * dibujado se realiza asincronamente por lo que el valor puede no coincidir con el ?ltimo
103
         * dibujado.
104
         */
105
        protected boolean                        isSupersampling = false;
106
        /**
107
         * Paso correspondiente al supersampling o subsampling que se est? aplicando en el ?ltimo dibujado.
108
         */
109
        protected int[] stepArrayX = null, stepArrayY = null;
110
        
111
        /**
112
         * Filtro para raster.
113
         * Permite eliminar la franja inutil alrededor de un raster girado o de
114
         * un mosaico de borde irregular.
115
         * 
116
         * Funciona bien solo con raster en tonos de gris, porque se basa que
117
         * el valor del pixel no supere un determinado valor 'umbral' que se
118
         * le pasa al constructor.
119
         * 
120
         * Desarrollado para 'limpiar' los bordes de los mosaicos del SIG
121
         * Oleicola. Para ese caso los par?metros del constructo son:
122
         * PixelFilter(0x10ffff00, 0xff000000, 0xf0f0f0);
123
         */
124
        protected PixelFilter                 tFilter = null;
125
        
126
        /**
127
         * Asignaci?n de banda del Rojo a una banda de la imagen
128
         */
129
        protected int                                 rBandNr = 1;
130
        
131
        /**
132
         * Asignaci?n de banda del Verde a una banda de la imagen
133
         */
134
        protected int                                 gBandNr = 1;
135
        
136
        /**
137
         * Asignaci?n de banda del Azul a una banda de la imagen
138
         */
139
        protected int                                 bBandNr = 1;
140
        
141
        /**
142
         * N?mero de bandas de la imagen
143
         */
144
        protected int                                 bandCount = 1;
145
        private int                                 dataType = DataBuffer.TYPE_BYTE;
146
        protected Palette                        palette = null;
147
        /**
148
         * Par?metros de transformaci?n del fichero .rmf. Estas variables tendr?n valores distinto
149
         * de 0 si la funci?n rmfExists() devuelve true.
150
         */
151
        protected double imageWidth = 0D, imageHeight = 0D;
152
        
153
        static {
154
                Messages.addResourceFamily("org.cresques.translations.text", "org.cresques.ui");
155
                supportedExtensions = new TreeMap();
156
                String os = System.getProperty("os.name");
157
                supportedExtensions.put("ecw",  EcwFile.class);
158
                supportedExtensions.put("jp2",  EcwFile.class);
159
                
160
                supportedExtensions.put("sid",  MrSidFile.class);
161

    
162
                supportedExtensions.put("bmp", GdalFile.class);
163
                supportedExtensions.put("gif", GdalFile.class);
164
                supportedExtensions.put("img", GdalFile.class);
165
                supportedExtensions.put("tif", GdalFile.class);
166
                supportedExtensions.put("tiff", GdalFile.class);
167
                supportedExtensions.put("jpg", GdalFile.class);
168
                supportedExtensions.put("png", GdalFile.class);
169
                supportedExtensions.put("vrt", GdalFile.class);
170
                
171
                supportedExtensions.put("dat",  GdalFile.class); // Envi
172
                supportedExtensions.put("lan",  GdalFile.class); // Erdas
173
                supportedExtensions.put("gis",  GdalFile.class); // Erdas
174
                supportedExtensions.put("pix",  GdalFile.class); // PCI Geomatics
175
                supportedExtensions.put("aux",  GdalFile.class); // PCI Geomatics
176
                //if(!os.toLowerCase().startsWith("windows"))
177
                supportedExtensions.put("adf",  GdalFile.class); // ESRI Grids
178
                supportedExtensions.put("mpr",  GdalFile.class); // Ilwis
179
                supportedExtensions.put("mpl",  GdalFile.class); // Ilwis
180
                supportedExtensions.put("map",  GdalFile.class); // PC Raster
181
                supportedExtensions.put("asc",  GdalFile.class); // PC Raster
182
                supportedExtensions.put("vrt",  GdalFile.class); 
183
        }
184
        
185
        /**
186
         * Factoria para abrir distintos tipos de raster.
187
         * 
188
         * @param proj Proyecci?n en la que est? el raster.
189
         * @param fName Nombre del fichero.
190
         * @return GeoRasterFile, o null si hay problemas.
191
         */
192
        public static GeoRasterFile openFile(IProjection proj, String fName) {
193
                String ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
194
                GeoRasterFile grf = null;
195

    
196
                //if (!supportedExtensions.containsKey(ext)) 
197
                        //return grf;
198
                Class clase = null;
199
                if (supportedExtensions.containsKey(ext))
200
                        clase = (Class) supportedExtensions.get(ext);
201
                else
202
                        clase = GdalFile.class;
203
                        
204
                
205
                Class [] args = {IProjection.class, String.class};
206
                try {
207
                        Constructor hazNuevo = clase.getConstructor(args);
208
                        Object [] args2 = {proj, fName};
209
                        grf = (GeoRasterFile) hazNuevo.newInstance(args2);
210
                        grf.setFileSize(new File(fName).length());
211
                } catch (SecurityException e) {
212
                        e.printStackTrace();
213
                } catch (NoSuchMethodException e) {
214
                        e.printStackTrace();
215
                } catch (IllegalArgumentException e) {
216
                        e.printStackTrace();
217
                } catch (InstantiationException e) {
218
                        e.printStackTrace();
219
                } catch (IllegalAccessException e) {
220
                        e.printStackTrace();
221
                } catch (InvocationTargetException e) {
222
                        System.err.println("Extension not supported!!!");
223
                        return null;
224
                }
225
                return grf;
226
        }
227
        
228
        /**
229
         * Registra una clase que soporta una extensi?n raster.
230
         * @param ext extensi?n soportada.
231
         * @param clase clase que la soporta.
232
         */
233
        public static void registerExtension(String ext, Class clase) {
234
                ext = ext.toLowerCase();
235
                System.out.println("RASTER: extension '"+ext+"' supported.");
236
                supportedExtensions.put(ext, clase);
237
        }
238
        
239
        /**
240
         * Tipo de fichero soportado.
241
         * Devuelve true si el tipo de fichero (extension) est? soportado, si no
242
         * devuelve false.
243
         * 
244
         * @param fName Fichero raster
245
         * @return  true si est? soportado, si no false.
246
          */
247
        public static boolean fileIsSupported(String fName) {
248
                //return true;
249
                String ext = fName.toLowerCase().substring(fName.lastIndexOf('.') + 1);
250
                return supportedExtensions.containsKey(ext);
251
        }
252
        
253
        /**
254
         * Constructor
255
         * @param proj        Proyecci?n
256
         * @param name        Nombre del fichero de imagen.
257
         */
258
        public GeoRasterFile(IProjection proj, String name) {
259
                super(proj, name);
260
        }
261
        
262
        /**
263
         * Carga un fichero raster. Puede usarse para calcular el extent e instanciar 
264
         * un objeto de este tipo.
265
         */
266
        abstract public GeoFile load();
267
        
268
        /**
269
         * Cierra el fichero y libera los recursos.
270
         */
271
        abstract public void close();
272
        
273
        /**
274
         * Obtiene la codificaci?n del fichero XML
275
         * @param file Nombre del fichero XML
276
         * @return Codificaci?n
277
         */
278
        private String readFileEncoding(String file){
279
                FileReader fr;
280
                String encoding = null;
281
                try
282
            {
283
                        fr = new FileReader(file);
284
                    BufferedReader br = new BufferedReader(fr);
285
                    char[] buffer = new char[100];
286
                    br.read(buffer);
287
                    StringBuffer st = new StringBuffer(new String(buffer));
288
                    String searchText = "encoding=\"";
289
                    int index = st.indexOf(searchText);
290
                    if (index>-1) {
291
                            st.delete(0, index+searchText.length());
292
                            encoding = st.substring(0, st.indexOf("\""));
293
                    }
294
                    fr.close();
295
            } catch(FileNotFoundException ex)        {
296
                    ex.printStackTrace();
297
            } catch (IOException e) {
298
                        e.printStackTrace();
299
                }
300
            return encoding;
301
        }
302
        
303
        private double[] parserExtent(KXmlParser parser) throws XmlPullParserException, IOException {                
304
                double originX = 0D, originY = 0D, w = 0D, h = 0D;
305
                double pixelSizeX = 0D, pixelSizeY = 0D;
306
                double shearX = 0D, shearY = 0D;
307
                
308
                boolean end = false;
309
            int tag = parser.next();
310
            while (!end) {
311
                    switch(tag) {
312
                        case KXmlParser.START_TAG:
313
                                if(parser.getName() != null){        
314
                                                if (parser.getName().equals(RasterMetaFileTags.POSX)){
315
                                                        originX = Double.parseDouble(parser.nextText());
316
                                                }else if (parser.getName().equals(RasterMetaFileTags.POSY)){
317
                                                        originY = Double.parseDouble(parser.nextText());
318
                                                }else if (parser.getName().equals(RasterMetaFileTags.PX_SIZE_X)){
319
                                                        pixelSizeX = Double.parseDouble(parser.nextText());
320
                                                }else if (parser.getName().equals(RasterMetaFileTags.PX_SIZE_Y)){
321
                                                        pixelSizeY = Double.parseDouble(parser.nextText());
322
                                                }else if (parser.getName().equals(RasterMetaFileTags.ROTX)){
323
                                                        shearX = Double.parseDouble(parser.nextText());
324
                                                }else if (parser.getName().equals(RasterMetaFileTags.ROTY)){
325
                                                        shearY = Double.parseDouble(parser.nextText());
326
                                                }else if (parser.getName().equals(RasterMetaFileTags.WIDTH)){
327
                                                        w = Double.parseDouble(parser.nextText());
328
                                                }else if (parser.getName().equals(RasterMetaFileTags.HEIGHT)){
329
                                                        h = Double.parseDouble(parser.nextText());
330
                                                }
331
                                        }                                
332
                                        break;
333
                         case KXmlParser.END_TAG:
334
                                 if (parser.getName().equals(RasterMetaFileTags.BBOX))
335
                                         end = true;
336
                                break;
337
                        case KXmlParser.TEXT:
338
                                break;
339
                    }
340
                    tag = parser.next();
341
            }
342
                
343
            double[] values = {originX, originY, w, h, pixelSizeX, pixelSizeY, shearX, shearY};
344
                return values;
345
        }
346
        
347
        /**
348
         * Obtiene la informaci?n de georreferenciaci?n asociada a la imagen en un fichero .rmf. Esta 
349
         * georreferenciaci?n tiene la caracteristica de que tiene prioridad sobre la de la imagen.
350
         * Es almacenada en la clase GeoFile en la variable virtualExtent.
351
         * @param file Fichero de metadatos .rmf
352
         */
353
        protected void readGeoInfo(String file){
354
                String rmf = file.substring(0, file.lastIndexOf(".") + 1) + "rmf";
355
                File rmfFile = new File(rmf);
356
                if(!rmfFile.exists())
357
                        return;
358
                
359
                boolean georefOk = false;
360
                
361
                FileReader fr = null;
362
                String v = null;
363
                try {
364
                        fr = new FileReader(rmf);
365
                        KXmlParser parser = new KXmlParser();
366
                        parser.setInput(new FileInputStream(rmf), readFileEncoding(rmf));
367
                        int tag = parser.nextTag();
368
                        if ( parser.getEventType() != KXmlParser.END_DOCUMENT ){                    
369
                                parser.require(KXmlParser.START_TAG, null, RasterMetaFileTags.MAIN_TAG);                            
370
                                while(tag != KXmlParser.END_DOCUMENT) {
371
                                        switch(tag) {
372
                                                case KXmlParser.START_TAG:
373
                                                        if (parser.getName().equals(RasterMetaFileTags.LAYER)) {
374
                                                                int layerListTag = parser.next();
375
                                                                boolean geoRefEnd = false;
376
                                                                while (!geoRefEnd){
377
                                                                        if(parser.getName() != null){
378
                                                                                if (parser.getName().equals(RasterMetaFileTags.PROJ)){
379
                                                                                        //System.out.println("PROJ:"+parser.nextText());
380
                                                                                } else if (parser.getName().equals(RasterMetaFileTags.BBOX)){
381
                                                                                        double[] values = parserExtent(parser);
382
                                                                                        rmfTransform = new AffineTransform(        values[4], values[7],
383
                                                                                                                                           values[6], values[5],
384
                                                                                                                                                                   values[0], values[1]);
385
                                                                                        georefOk = true;
386
                                                                                } else if (parser.getName().equals(RasterMetaFileTags.DIM)){
387
                                                                                        boolean DimEnd = false;
388
                                                                                        while (!DimEnd){
389
                                                                                                layerListTag = parser.next();
390
                                                                                                if(parser.getName() != null){        
391
                                                                                                        if (parser.getName().equals(RasterMetaFileTags.PX_WIDTH)){
392
                                                                                                                imageWidth = Double.parseDouble(parser.nextText());
393
                                                                                                        }else if (parser.getName().equals(RasterMetaFileTags.PX_HEIGHT)){
394
                                                                                                                imageHeight = Double.parseDouble(parser.nextText());
395
                                                                                                                DimEnd = true;
396
                                                                                                        }                                                                                                        
397
                                                                                                }
398
                                                                                        }
399
                                                                                        geoRefEnd = true;
400
                                                                                }
401
                                                                        }
402
                                                                        layerListTag = parser.next();
403
                                                                }
404
                                                        }
405
                                                        break;
406
                                                case KXmlParser.END_TAG:                                                        
407
                                                        break;
408
                                                case KXmlParser.TEXT:                                                        
409
                                                        break;
410
                                        }
411
                                        tag = parser.next();
412
                                }
413
                                parser.require(KXmlParser.END_DOCUMENT, null, null);
414
                        }
415
                        
416
                        if(georefOk){
417
                                rmfExists = true;
418
                                setExtentTransform(        rmfTransform.getTranslateX(), rmfTransform.getTranslateY(), 
419
                                                                        rmfTransform.getScaleX(), rmfTransform.getScaleY());
420
                                createExtentsFromRMF(        rmfTransform.getTranslateX(), rmfTransform.getTranslateY(), 
421
                                                                                rmfTransform.getScaleX(), rmfTransform.getScaleY(), 
422
                                                                                imageWidth, imageHeight, 
423
                                                                                rmfTransform.getShearX(), rmfTransform.getShearY());
424
                        }
425
                        
426
                } catch (FileNotFoundException fnfEx) {
427
                } catch (XmlPullParserException xmlEx) {
428
                        xmlEx.printStackTrace();
429
                } catch (IOException e) {
430
                } 
431
                try{
432
                        if(fr != null)
433
                                fr.close();
434
                }catch(IOException ioEx){
435
                        //No est? abierto el fichero por lo que no hacemos nada
436
                }
437
        }
438

    
439
        /**
440
         * Asigna una transformaci?n al raster para que se tenga en cuenta en la asignaci?n del setView. 
441
         * Esta asignaci?n recalcula el extent, el requestExtent y asigna el AffineTransform que se 
442
         * usar? para la transformaci?n. Esta transformaci?n ser? considerada como si la imagen tuviera 
443
         * asociado un rmf.
444
         * @param t Transformaci?n af?n a aplicar
445
         */
446
        public void setAffineTransform(AffineTransform t){
447
                rmfExists = true;
448
                rmfTransform = (AffineTransform)t.clone();
449
                setExtentTransform(t.getTranslateX(), t.getTranslateY(), t.getScaleX(), t.getScaleY());
450
                createExtentsFromRMF(        t.getTranslateX(), t.getTranslateY(), t.getScaleX(), t.getScaleY(), 
451
                                                                this.getWidth(), this.getHeight(), 
452
                                                                t.getShearX(), t.getShearY());
453
        }
454
        
455
        /**
456
         * Asigna una transformaci?n al raster para que se tenga en cuenta en la asignaci?n del setView. 
457
         * Esta asignaci?n recalcula el extent, el requestExtent y asigna el AffineTransform que se 
458
         * usar? para la transformaci?n. Esta transformaci?n ser? considerada como si la imagen tuviera 
459
         * asociado un rmf.
460
         * @param originX Coordenada X de origen del raster
461
         * @param originY Coordenada Y de origen del raster
462
         * @param pixelSizeX Tama?o de pixel en X
463
         * @param pixelSizeY Tama?o de pixel en Y
464
         * @param imageWidth Ancho del raster en pixels
465
         * @param imageHeight Alto del raster en pixels
466
         * @param shearX Shearing en X
467
         * @param shearY Shearing en Y
468
         */
469
        public void setAffineTransform(        double originX, double originY, double pixelSizeX, 
470
                                                                                double pixelSizeY, double shearX, double shearY){
471
                rmfExists = true;
472
                rmfTransform.setToTranslation(originX, originY);
473
                rmfTransform.shear(shearX, shearY);
474
                rmfTransform.scale(pixelSizeX, pixelSizeY);
475
                setExtentTransform(originX, originY, pixelSizeX, pixelSizeY);
476
                createExtentsFromRMF(        originX, originY, pixelSizeX, pixelSizeY, 
477
                                                                imageWidth, imageHeight, shearX, shearY);
478
        }
479
        
480
        /**
481
         * Obtiene la matriz de transformaci?n que se aplica sobre la visualizaci?n 
482
         * del raster.
483
         * @return Matriz de transformaci?n.
484
         */
485
        public AffineTransform getAffineTransform(){
486
                return rmfTransform;
487
        }
488
        
489
        /**
490
         * Elimina la matriz de transformaci?n asociada al raster y que se tiene en cuenta para
491
         * el setView. Este reseteo tendr? en cuenta que si el raster tiene asociado un rmf
492
         * esta transformaci?n no ser? eliminada sino que se asignar? la correspondiente al rmf
493
         * existente.  
494
         * @return devuelve true si tiene fichero rmf asociado y false si no lo tiene.
495
         */
496
        public boolean resetAffineTransform(){
497
                rmfExists = false;
498
                rmfTransform.setToIdentity();
499
                
500
                //Crea los extent iniciales
501
                load();
502
                
503
                //Lee y carga el rmf si existe
504
                readGeoInfo(this.getName());
505
                
506
                if(rmfExists)
507
                        return true;
508
                else
509
                        return false;
510
        }
511
        
512
        /**
513
         * <P>
514
         * Calcula el extent de la imagen a partir del fichero rmf con y sin rotaci?n. El extent con rotaci?n corresponde
515
         * a la variable extent que contiene el extent verdadero marcado por el fichero de georreferenciaci?n .rmf. El extent
516
         * sin rotaci?n requestExtent es utilizado para realizar la petici?n ya que la petici?n al driver no se puede
517
         * hacer con coordenadas rotadas.
518
         * 
519
         * El calculo de la bounding box rotada lo hace con los valores de transformaci?n leidos desde el fichero .rmf.
520
         * </p>
521
         * <P>
522
         * Para el calculo de una esquina aplicamos la formula siguiente:<BR>
523
         * PtoX = originX + pixelSizeX * x + shearX * y;<BR>
524
         * PtoY = originY + shearY * x + pixelSizeY * y;<BR>
525
         * Aplicandolo a las cuatro esquinas sustituimos en cada una de ellas por.
526
         * </P>
527
         * <UL> 
528
         * <LI>Esquina superior izquierda: x = 0; y = 0;</LI>
529
         * <LI>Esquina superior derecha: x = MaxX; y = 0;</LI>
530
         * <LI>Esquina inferior izquierda: x = 0; y = MaxY;</LI>
531
         * <LI>Esquina inferior derecha: x = MaxX; y = MaxY;</LI>
532
         * </UL> 
533
         * <P>
534
         * quedandonos en los cuatro casos:
535
         * </P>
536
         * <UL> 
537
         * <LI>Esquina superior izquierda: originX; originY;</LI>
538
         * <LI>Esquina superior derecha: PtoX = originX + pixelSizeX * x; PtoY = originY + shearY * x;</LI>
539
         * <LI>Esquina inferior izquierda:  PtoX = originX + shearX * y; PtoY = originY + pixelSizeY * y;</LI>
540
         * <LI>Esquina inferior derecha: PtoX = originX + pixelSizeX * x + shearX * y; PtoY = originY + shearY * x + pixelSizeY * y;</LI>
541
         * </UL>
542
         * 
543
         * <P>
544
         * El calculo de la bounding box se realizar? de la misma forma pero anulando los parametros de shearing.
545
         * </P>
546
         * 
547
         * @param originX Coordenada X de origen del raster
548
         * @param originY Coordenada Y de origen del raster
549
         * @param pixelSizeX Tama?o de pixel en X
550
         * @param pixelSizeY Tama?o de pixel en Y
551
         * @param imageWidth Ancho del raster en pixels
552
         * @param imageHeight Alto del raster en pixels
553
         * @param shearX Shearing en X
554
         * @param shearY Shearing en Y
555
         */
556
        private void createExtentsFromRMF(        double originX, double originY, double pixelSizeX, double pixelSizeY, 
557
                                                                                double imageWidth, double imageHeight, double shearX, double shearY){
558
                                
559
                Point2D p1 = new Point2D.Double(originX, originY);
560
                Point2D p2 = new Point2D.Double(originX + shearX * imageHeight, originY + pixelSizeY * imageHeight);
561
                Point2D p3 = new Point2D.Double(originX + pixelSizeX * imageWidth, originY + shearY * imageWidth);
562
                Point2D p4 = new Point2D.Double(originX + pixelSizeX * imageWidth + shearX * imageHeight, originY + pixelSizeY * imageHeight + shearY * imageWidth);
563
                
564
                double minX = Math.min(Math.min(p1.getX(), p2.getX()), Math.min(p3.getX(), p4.getX()));
565
                double minY = Math.min(Math.min(p1.getY(), p2.getY()), Math.min(p3.getY(), p4.getY()));
566
                double maxX = Math.max(Math.max(p1.getX(), p2.getX()), Math.max(p3.getX(), p4.getX()));
567
                double maxY = Math.max(Math.max(p1.getY(), p2.getY()), Math.max(p3.getY(), p4.getY()));
568
                extent = new Extent(minX, minY, maxX, maxY);
569
                requestExtent = new Extent(originX, originY, originX + (pixelSizeX * imageWidth), originY + (pixelSizeY * imageHeight));
570
        }
571
        
572
        /**
573
         * Calcula la transformaci?n que se produce sobre la vista cuando la imagen tiene un fichero .rmf
574
         * asociado. Esta transformaci?n tiene diferencias entre los distintos formatos por lo que debe calcularla
575
         * el driver correspondiente.
576
         * @param originX Origen de la imagen en la coordenada X
577
         * @param originY Origen de la imagen en la coordenada Y
578
         */
579
        abstract public void setExtentTransform(double originX, double originY, double psX, double psY);
580
        
581
        public static PxContour getContour(String fName, String name, IProjection proj) {
582
                PxContour contour = null;
583
                return contour;
584
        }
585
                
586
        /**
587
         * Obtiene el ancho de la imagen
588
         * @return Ancho de la imagen
589
         */
590
        abstract public int getWidth();
591
        
592
        /**
593
         * Obtiene el ancho de la imagen
594
         * @return Ancho de la imagen
595
         */
596
        abstract public int getHeight();
597

    
598
        /**
599
         * Reproyecci?n.
600
         * @param rp        Coordenadas de la transformaci?n
601
         */
602
        abstract public void reProject(ICoordTrans rp);
603

    
604
        /**
605
         * Asigna un nuevo Extent 
606
         * @param e        Extent
607
         */
608
        abstract public void setView(Extent e);
609
        
610
        /**
611
         * Obtiene el extent asignado
612
         * @return        Extent
613
         */
614
        abstract public Extent getView();
615
        
616
        public void setTransparency(boolean t) {
617
                doTransparency = t;
618
                tFilter = new PixelFilter(255);
619
        }
620
        
621
        /**
622
         * Asigna un valor de transparencia
623
         * @param t        Valor de transparencia
624
         */
625
        public void setTransparency(int t ) {
626
                doTransparency = true;
627
                tFilter = new SimplePixelFilter(255 - t);
628
        }
629
        
630
        public boolean getTransparency() { return doTransparency; }
631
        
632
        public void setAlpha(int alpha) {
633
                if (!doTransparency) setTransparency(255 - alpha);
634
                else tFilter.setAlpha(alpha);
635
        }
636
        public int getAlpha() {
637
                if (tFilter == null)
638
                        return 255;
639
                return tFilter.getAlpha();
640
        }
641
        
642
        public void setUpdatable(Component c) { updatable = c; }
643
        
644
        /**
645
         * Actualiza la imagen
646
         * @param width        ancho
647
         * @param height        alto
648
         * @param rp        Reproyecci?n
649
         * @return        img
650
         */
651
        abstract public Image updateImage(int width, int height, ICoordTrans rp);
652

    
653
        /**
654
         * Obtiene el valor del raster en la coordenada que se le pasa.
655
         * El valor ser? Double, Int, Byte, etc. dependiendo del tipo de
656
         * raster.
657
         * @param x        coordenada X
658
         * @param y coordenada Y
659
         * @return
660
         */
661
        abstract public Object getData(int x, int y, int band);
662

    
663
        /**
664
         * Actualiza la/s banda/s especificadas en la imagen.
665
         * @param width                ancho
666
         * @param height        alto
667
         * @param rp                reproyecci?n
668
         * @param img                imagen
669
         * @param flags                que bandas [ RED_BAND | GREEN_BAND | BLUE_BAND ]
670
         * @return                img
671
         * @throws SupersamplingNotSupportedException
672
         */
673
        abstract public Image updateImage(int width, int height, ICoordTrans rp, Image img, int origBand, int destBand)throws SupersamplingNotSupportedException;
674

    
675
        public int getBandCount() { return bandCount; }
676
        
677
        /**
678
         * Asocia un colorBand al rojo, verde o azul.
679
         * @param flag cual (o cuales) de las bandas.
680
         * @param nBand        que colorBand
681
         */
682
        
683
        public void setBand(int flag, int bandNr) {
684
                if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) rBandNr = bandNr;
685
                if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) gBandNr = bandNr;
686
                if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) bBandNr = bandNr;
687
        }
688

    
689
        /**
690
         * Devuelve el colorBand activo en la banda especificada.
691
         * @param flag banda.
692
         */
693
        
694
        public int getBand(int flag) {
695
                if (flag == GeoRasterFile.RED_BAND) return rBandNr;
696
                if (flag == GeoRasterFile.GREEN_BAND) return gBandNr;
697
                if (flag == GeoRasterFile.BLUE_BAND) return bBandNr;
698
                return -1;
699
        }
700
        
701
        /**
702
         * @return Returns the dataType.
703
         */
704
        public int getDataType() {
705
                return dataType;
706
        }
707
        
708
        /**
709
         * @param dataType The dataType to set.
710
         */
711
        public void setDataType(int dataType) {
712
                this.dataType = dataType;
713
        }
714

    
715
        public IObjList getObjects() {
716
                // TODO hay que a?adir el raster a la lista de objetos
717
                IObjList oList = new PxObjList(proj);
718
                return oList;
719
        }
720
        
721
        /**
722
         * Calcula los par?metros de un worl file a partir de las esquinas del raster.
723
         *    1. X pixel size A
724
         *    2. X rotation term D
725
         *    3. Y rotation term B
726
         *    4. Y pixel size E
727
         *    5. X coordinate of upper left corner C
728
         *    6. Y coordinate of upper left corner F
729
         * where the real-world coordinates x',y' can be calculated from
730
         * the image coordinates x,y with the equations
731
         *  x' = Ax + By + C and y' = Dx + Ey + F.
732
         *  The signs of the first 4 parameters depend on the orientation
733
         *  of the image. In the usual case where north is more or less
734
         *  at the top of the image, the X pixel size will be positive
735
         *  and the Y pixel size will be negative. For a south-up image,
736
         *  these signs would be reversed.
737
         * 
738
         * You can calculate the World file parameters yourself based
739
         * on the corner coordinates. The X and Y pixel sizes can be
740
         *  determined simply by dividing the distance between two
741
         *  adjacent corners by the number of columns or rows in the image.
742
         *  The rotation terms are calculated with these equations:
743
         * 
744
         *  # B = (A * number_of_columns + C - lower_right_x') / number_of_rows * -1
745
         *  # D = (E * number_of_rows + F - lower_right_y') / number_of_columns * -1
746
         * 
747
         * @param corner (tl, tr, br, bl)
748
         * @return
749
         */
750
        public static double [] cornersToWorldFile(Point2D [] esq, Dimension size) {
751
                double a=0,b=0,c=0,d=0,e=0,f=0;
752
                double x1 = esq[0].getX(), y1 = esq[0].getY();
753
                double x2 = esq[1].getX(), y2 = esq[1].getY();
754
                double x3 = esq[2].getX(), y3 = esq[2].getY();
755
                double x4 = esq[3].getX(), y4 = esq[3].getY();
756
                // A: X-scale
757
                a = Math.abs( Math.sqrt( (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
758
                      / size.getWidth());
759

    
760
                // E: negative Y-scale
761
                e =  - Math.abs(Math.sqrt((x1-x4)*(x1-x4)+
762
                      (y1-y4)*(y1-y4))/size.getHeight());
763

    
764
                // C, F: upper-left coordinates
765
                c = x1;
766
                f = y1;
767
                
768
                // B & D: rotation parameters
769
                b = (a * size.getWidth() + c - x3 ) / size.getHeight() * -1;
770
                d = (e * size.getHeight() + f - y3 ) / size.getWidth() * -1;
771

    
772
                double [] wf = {a,d,b,e,c,f}; 
773
                return wf;  
774
        }
775
    public static String printWF(String fName, Point2D [] esq, Dimension sz) {
776
            double [] wf = GeoRasterFile.cornersToWorldFile(esq, sz);
777
            System.out.println("wf para "+fName);
778
            System.out.println(esq+"\n"+sz);
779
            String wfData = "";
780
            for (int i=0; i<6; i++)
781
                    wfData += wf[i]+"\n";
782
                System.out.println(wfData);
783
                return wfData;
784
    }
785
    
786
    public static void saveWF(String fName, String data) throws IOException {
787
            FileWriter fw = new FileWriter(fName);
788
            fw.write(data);
789
            fw.flush();
790
            fw.close();
791
    }
792

    
793
        /**
794
         * Cosulta si hay que verificar la relaci?n de aspecto de la imagen, es decir comprueba que el ancho/alto
795
         * pasados a updateImage coinciden con el ancho/alto solicitado en setView a la imagen
796
         * @return true si est? verificando la relaci?n de aspecto. 
797
         */
798
        public boolean mustVerifySize() {
799
                return verifySize;
800
        }
801

    
802
        /**
803
         * Asigna el flag que dice si hay que verificar la relaci?n de aspecto de la imagen, es decir 
804
         * comprueba que el ancho/alto pasados a updateImage coinciden con el ancho/alto solicitado 
805
         * en setView a la imagen.
806
         * @return true si est? verificando la relaci?n de aspecto. 
807
         */
808
        public void setMustVerifySize(boolean verifySize) {
809
                this.verifySize = verifySize;
810
        }
811

    
812
        /**
813
         * Obtiene una ventana de datos de la imagen a partir de coordenadas reales. 
814
         * No aplica supersampleo ni subsampleo sino que devuelve una matriz de igual tama?o a los
815
         * pixeles de disco. 
816
         * @param x Posici?n X superior izquierda
817
         * @param y Posici?n Y superior izquierda
818
         * @param w Ancho en coordenadas reales
819
         * @param h Alto en coordenadas reales
820
         * @param rasterBuf        Buffer de datos
821
         * @param bandList
822
         * @return Buffer de datos
823
         */
824
        abstract public RasterBuf getWindowRaster(double x, double y, double w, double h, BandList bandList, RasterBuf rasterBuf);
825
        
826
        /**
827
         * Obtiene una ventana de datos de la imagen a partir de coordenadas pixel. 
828
         * No aplica supersampleo ni subsampleo sino que devuelve una matriz de igual tama?o a los
829
         * pixeles de disco. 
830
         * @param x Posici?n X superior izquierda
831
         * @param y Posici?n Y superior izquierda
832
         * @param w Ancho en coordenadas reales
833
         * @param h Alto en coordenadas reales
834
         * @param rasterBuf        Buffer de datos
835
         * @param bandList
836
         * @return Buffer de datos
837
         */
838
        abstract public RasterBuf getWindowRaster(int x, int y, int w, int h, BandList bandList, RasterBuf rasterBuf);
839

    
840
        /**
841
         * Obtiene una ventana de datos de la imagen a partir de coordenadas reales. 
842
         * Se aplica supersampleo o subsampleo dependiendo del tama?o del buffer especificado.
843
         * 
844
         * @param minX Posici?n m?nima X superior izquierda
845
         * @param minY Posici?n m?nima Y superior izquierda
846
         * @param maxX Posici?n m?xima X inferior derecha
847
         * @param maxY Posici?n m?xima Y inferior derecha
848
         * @param bufWidth Ancho del buffer de datos
849
         * @param bufHeight Alto del buffer de datos
850
         * @param rasterBuf        Buffer de datos
851
         * @param bandList
852
         * @return Buffer de datos
853
         */
854
        abstract public RasterBuf getWindowRaster(double minX, double minY, double maxX, double maxY, int bufWidth, int bufHeight, BandList bandList, RasterBuf rasterBuf);
855
        
856
        /**
857
         * Obtiene una ventana de datos de la imagen a partir de coordenadas reales. 
858
         * No aplica supersampleo ni subsampleo sino que devuelve una matriz de igual tama?o a los
859
         * pixeles de disco. 
860
         * @param x Posici?n X superior izquierda
861
         * @param y Posici?n Y superior izquierda
862
         * @param w Ancho en coordenadas reales
863
         * @param h Alto en coordenadas reales
864
         * @param rasterBuf        Buffer de datos
865
         * @param bandList
866
         * @return Buffer de datos
867
         */
868
        abstract public RasterBuf getWindowRasterWithNoData(double x, double y, double w, double h, BandList bandList, RasterBuf rasterBuf);
869
        
870
        abstract public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band);
871
        
872
        abstract public int getBlockSize();
873
        
874
        /**
875
         * Obtiene el objeto que contiene los metadatos. Este m?todo debe ser redefinido por los
876
         * drivers si necesitan devolver metadatos. 
877
         * @return
878
         */
879
        public Metadata getMetadata(){
880
                return null;
881
        }
882
        
883
        /**
884
         * Asigna un extent temporal que puede coincidir con el de la vista. Esto es 
885
         * util para cargar imagenes sin georreferenciar ya que podemos asignar el extent
886
         * que queramos para ajustarnos a una vista concreta
887
         * @param tempExtent The tempExtent to set.
888
         */
889
        public void setExtent(Extent ext) {
890
                this.extent = ext;
891
        }
892
        
893
        /**
894
         * Dice si el fichero tiene georreferenciaci?n o no.
895
         * @return true si tiene georreferenciaci?n y false si no la tiene
896
         */
897
        public boolean isGeoreferenced(){
898
                return true;
899
        }
900

    
901
        /**
902
         * Informa de si el driver ha supersampleado en el ?ltimo dibujado. Es el driver el que colocar?
903
         * el valor de esta variable cada vez que dibuja. Debe tenerse especial cuidado ya que est? consulta no es adecuada desde gvSIG ya que el
904
         * dibujado se realiza asincronamente por lo que el valor puede no coincidir con el ?ltimo
905
         * dibujado.
906
         * @return true si se ha supersampleado y false si no se ha hecho.
907
         */
908
        public boolean isSupersampling() {
909
                return this.isSupersampling;
910
        }
911
        
912
        /**
913
         * Asigna el valor del paso en X e Y aplicado en el ?ltimo dibujado. Es el driver el que colocar?
914
         * el valor de esta variable cada vez que dibuja. 
915
         * @param stepx Paso en X
916
         * @param stepy Paso en Y
917
         */
918
        public void setStep(int[] stepArrayx, int[] stepArrayy){
919
                this.stepArrayX = stepArrayx;
920
                this.stepArrayY = stepArrayy;
921
        }
922
        
923
        /**
924
         * Obtiene el valor del paso en X aplicado en el ?ltimo dibujado. Es el driver el que colocar?
925
         * el valor de esta variable cada vez que dibuja. 
926
         * @return
927
         */
928
        public int[] getStepX(){
929
                return stepArrayX;
930
        }
931
        
932
        /**
933
         * Obtiene el valor del paso en Y aplicado en el ?ltimo dibujado. Es el driver el que colocar?
934
         * el valor de esta variable cada vez que dibuja. 
935
         * @return
936
         */
937
        public int[] getStepY(){
938
                return stepArrayY;
939
        }
940

    
941
        /**
942
         * Obtiene el objeto paleta. Esta paleta es la que tiene adjunta el fichero de disco. Si es
943
         * null este objeto quiere decir que no tiene paleta para su visualizaci?n. 
944
         * @return Palette
945
         */
946
        public Palette getPalette() {
947
                return palette;
948
        }
949

    
950
        /**
951
         * Asigna el objeto paleta. Esta paleta es la que tiene adjunta el fichero de disco. Si es
952
         * null este objeto quiere decir que no tiene paleta para su visualizaci?n. 
953
         * @param Palette
954
         */
955
        public void setPalette(Palette palette) {
956
                this.palette = palette;
957
        }
958
        
959
        /**
960
         * M?todo que indica si existe un fichero .rmf asociado al GeoRasterFile.
961
         * @return
962
         */
963
        public boolean rmfExists(){
964
                return this.rmfExists;
965
        }
966
                
967
        /**
968
         * Obtiene los par?metros de la transformaci?n af?n que corresponde con los elementos de
969
         * un fichero tfw.
970
         * <UL> 
971
         * <LI>[1]tama?o de pixel en X</LI>
972
         * <LI>[2]rotaci?n en X</LI>
973
         * <LI>[4]rotaci?n en Y</LI>
974
         * <LI>[5]tama?o de pixel en Y</LI>
975
         * <LI>[0]origen en X</LI>
976
         * <LI>[3]origen en Y</LI>
977
         * </UL>
978
         * Este m?todo debe ser reimplementado por el driver si tiene esta informaci?n. En principio
979
         * Gdal es capaz de proporcionarla de esta forma.
980
         * @return vector de double con los elementos de la transformaci?n af?n.
981
         */
982
        public double[] getTransform(){return null;}
983
        
984
        /**
985
         * Convierte un punto desde coordenadas pixel a coordenadas del mundo.
986
         * @param pt Punto a transformar
987
         * @return punto transformado en coordenadas del mundo
988
         */
989
        abstract public Point2D rasterToWorld(Point2D pt);
990
        
991
        /**
992
         * Convierte un punto desde del mundo a coordenadas pixel.
993
         * @param pt Punto a transformar
994
         * @return punto transformado en coordenadas pixel
995
         */
996
        abstract public Point2D worldToRaster(Point2D pt);
997
        
998
        /**
999
         * Vuelve a leer la paleta del fichero por si ha sido modificada
1000
         *
1001
         */
1002
        public void readPalette(){}
1003
}