Statistics
| Revision:

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

History | View | Annotate | Download (33.6 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
        private 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
        }
183
        
184
        /**
185
         * Factoria para abrir distintos tipos de raster.
186
         * 
187
         * @param proj Proyecci?n en la que est? el raster.
188
         * @param fName Nombre del fichero.
189
         * @return GeoRasterFile, o null si hay problemas.
190
         */
191
        public static GeoRasterFile openFile(IProjection proj, String fName) {
192
                String ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
193
                GeoRasterFile grf = null;
194

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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