Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libCq CMS for java.old / src / org / cresques / io / GeoRasterFile.java @ 8281

History | View | Annotate | Download (24.5 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.Point2D;
30
import java.awt.image.DataBuffer;
31
import java.io.BufferedReader;
32
import java.io.File;
33
import java.io.FileInputStream;
34
import java.io.FileNotFoundException;
35
import java.io.FileReader;
36
import java.io.FileWriter;
37
import java.io.IOException;
38
import java.lang.reflect.Constructor;
39
import java.lang.reflect.InvocationTargetException;
40
import java.util.TreeMap;
41

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

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

    
67
public abstract class GeoRasterFile extends GeoFile {
68
        
69
        /**
70
         * Flag que representa a la banda del Rojo
71
         */
72
        public static final int         RED_BAND        = 0x01;
73
        
74
        /**
75
         * Flag que representa a la banda del Verde
76
         */
77
        public static final int         GREEN_BAND        = 0x02;
78
        
79
        /**
80
         * Flag que representa a la banda del Azul
81
         */
82
        public static final int         BLUE_BAND        = 0x04;
83
        private static TreeMap                 supportedExtensions = null;
84
        protected Component                 updatable = null;
85
        protected boolean                         doTransparency = false;
86
        private boolean                                verifySize = false;
87
        
88
        /**
89
         * Filtro para raster.
90
         * Permite eliminar la franja inutil alrededor de un raster girado o de
91
         * un mosaico de borde irregular.
92
         * 
93
         * Funciona bien solo con raster en tonos de gris, porque se basa que
94
         * el valor del pixel no supere un determinado valor 'umbral' que se
95
         * le pasa al constructor.
96
         * 
97
         * Desarrollado para 'limpiar' los bordes de los mosaicos del SIG
98
         * Oleicola. Para ese caso los par?metros del constructo son:
99
         * PixelFilter(0x10ffff00, 0xff000000, 0xf0f0f0);
100
         */
101
        protected PixelFilter                 tFilter = null;
102
        
103
        /**
104
         * Asignaci?n de banda del Rojo a una banda de la imagen
105
         */
106
        protected int                                 rBandNr = 1;
107
        
108
        /**
109
         * Asignaci?n de banda del Verde a una banda de la imagen
110
         */
111
        protected int                                 gBandNr = 1;
112
        
113
        /**
114
         * Asignaci?n de banda del Azul a una banda de la imagen
115
         */
116
        protected int                                 bBandNr = 1;
117
        
118
        /**
119
         * N?mero de bandas de la imagen
120
         */
121
        protected int                                 bandCount = 1;
122
        private int                                 dataType = DataBuffer.TYPE_BYTE;
123
        /**
124
         * Par?metros de transformaci?n del fichero .rmf. Estas variables tendr?n valores distinto
125
         * de 0 si la funci?n rmfExists() devuelve true.
126
         */
127
        protected double originX = 0D, originY = 0D, w = 0D, h = 0D;
128
        protected double pixelSizeX = 0D, pixelSizeY = 0D;
129
        protected double imageWidth = 0D, imageHeight = 0D;
130
        protected double shearX = 0D, shearY = 0D;
131

    
132
        static {
133
                supportedExtensions = new TreeMap();
134
                supportedExtensions.put("ecw",  EcwFile.class);
135
                supportedExtensions.put("jp2",  EcwFile.class);
136
                
137
                supportedExtensions.put("sid",  MrSidFile.class);
138

    
139
                supportedExtensions.put("bmp", GdalFile.class);
140
                supportedExtensions.put("gif", GdalFile.class);
141
                supportedExtensions.put("img", GdalFile.class);
142
                supportedExtensions.put("tif", GdalFile.class);
143
                supportedExtensions.put("tiff", GdalFile.class);
144
                supportedExtensions.put("jpg", GdalFile.class);
145
                supportedExtensions.put("png", GdalFile.class);
146
                //supportedExtensions.put("jpg",  TifGeoRefFile.class);
147
                //supportedExtensions.put("png",  TifGeoRefFile.class);
148
                //supportedExtensions.put("dat",  GdalFile.class);
149
        }
150
        
151
        /**
152
         * Factoria para abrir distintos tipos de raster.
153
         * 
154
         * @param proj Proyecci?n en la que est? el raster.
155
         * @param fName Nombre del fichero.
156
         * @return GeoRasterFile, o null si hay problemas.
157
         */
158
        public static GeoRasterFile openFile(IProjection proj, String fName) {
159
                String ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
160
                GeoRasterFile grf = null;
161
                // TODO NotSupportedExtensionException
162
                if (!supportedExtensions.containsKey(ext)) return grf;
163
                /**/
164
                Class clase = (Class) supportedExtensions.get(ext);
165
                Class [] args = {IProjection.class, String.class};
166
                try {
167
                        Constructor hazNuevo = clase.getConstructor(args);
168
                        Object [] args2 = {proj, fName};
169
                        grf = (GeoRasterFile) hazNuevo.newInstance(args2);
170
                        grf.setFileSize(new File(fName).length());
171
                } catch (SecurityException e) {
172
                        // TODO Auto-generated catch block
173
                        e.printStackTrace();
174
                } catch (NoSuchMethodException e) {
175
                        // TODO Auto-generated catch block
176
                        e.printStackTrace();
177
                } catch (IllegalArgumentException e) {
178
                        // TODO Auto-generated catch block
179
                        e.printStackTrace();
180
                } catch (InstantiationException e) {
181
                        // TODO Auto-generated catch block
182
                        e.printStackTrace();
183
                } catch (IllegalAccessException e) {
184
                        // TODO Auto-generated catch block
185
                        e.printStackTrace();
186
                } catch (InvocationTargetException e) {
187
                        // TODO Auto-generated catch block
188
                        e.printStackTrace();
189
                }
190
                 
191
                return grf;
192
        }
193
        
194
        /**
195
         * Registra una clase que soporta una extensi?n raster.
196
         * @param ext extensi?n soportada.
197
         * @param clase clase que la soporta.
198
         */
199
        public static void registerExtension(String ext, Class clase) {
200
                ext = ext.toLowerCase();
201
                System.out.println("RASTER: extension '"+ext+"' supported.");
202
                supportedExtensions.put(ext, clase);
203
        }
204
        
205
        /**
206
         * Tipo de fichero soportado.
207
         * Devuelve true si el tipo de fichero (extension) est? soportado, si no
208
         * devuelve false.
209
         * 
210
         * @param fName Fichero raster
211
         * @return  true si est? soportado, si no false.
212
          */
213
        public static boolean fileIsSupported(String fName) {
214
                String ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
215
                return supportedExtensions.containsKey(ext);
216
        }
217
        
218
        /**
219
         * Constructor
220
         * @param proj        Proyecci?n
221
         * @param name        Nombre del fichero de imagen.
222
         */
223
        public GeoRasterFile(IProjection proj, String name) {
224
                super(proj, name);
225
        }
226
        
227
        /**
228
         * Carga un fichero raster. Puede usarse para calcular el extent e instanciar 
229
         * un objeto de este tipo.
230
         */
231
        abstract public GeoFile load();
232
        
233
        /**
234
         * Cierra el fichero y libera los recursos.
235
         */
236
        abstract public void close();
237
        
238
        /**
239
         * Obtiene la codificaci?n del fichero XML
240
         * @param file Nombre del fichero XML
241
         * @return Codificaci?n
242
         */
243
        private String readFileEncoding(String file){
244
                FileReader fr;
245
                String encoding = null;
246
                try
247
            {
248
                        fr = new FileReader(file);
249
                    BufferedReader br = new BufferedReader(fr);
250
                    char[] buffer = new char[100];
251
                    br.read(buffer);
252
                    StringBuffer st = new StringBuffer(new String(buffer));
253
                    String searchText = "encoding=\"";
254
                    int index = st.indexOf(searchText);
255
                    if (index>-1) {
256
                            st.delete(0, index+searchText.length());
257
                            encoding = st.substring(0, st.indexOf("\""));
258
                    }
259
                    fr.close();
260
            } catch(FileNotFoundException ex)        {
261
                    ex.printStackTrace();
262
            } catch (IOException e) {
263
                        e.printStackTrace();
264
                }
265
            return encoding;
266
        }
267
        
268
        private double[] parserExtent(KXmlParser parser) throws XmlPullParserException, IOException {                
269
                double originX = 0D, originY = 0D, w = 0D, h = 0D;
270
                double pixelSizeX = 0D, pixelSizeY = 0D;
271
                double shearX = 0D, shearY = 0D;
272
                
273
                boolean end = false;
274
            int tag = parser.next();
275
            while (!end) {
276
                    switch(tag) {
277
                        case KXmlParser.START_TAG:
278
                                if(parser.getName() != null){        
279
                                                if (parser.getName().equals(RasterMetaFileTags.POSX)){
280
                                                        originX = Double.parseDouble(parser.nextText());
281
                                                }else if (parser.getName().equals(RasterMetaFileTags.POSY)){
282
                                                        originY = Double.parseDouble(parser.nextText());
283
                                                }else if (parser.getName().equals(RasterMetaFileTags.PX_SIZE_X)){
284
                                                        pixelSizeX = Double.parseDouble(parser.nextText());
285
                                                }else if (parser.getName().equals(RasterMetaFileTags.PX_SIZE_Y)){
286
                                                        pixelSizeY = Double.parseDouble(parser.nextText());
287
                                                }else if (parser.getName().equals(RasterMetaFileTags.ROTX)){
288
                                                        shearX = Double.parseDouble(parser.nextText());
289
                                                }else if (parser.getName().equals(RasterMetaFileTags.ROTY)){
290
                                                        shearY = Double.parseDouble(parser.nextText());
291
                                                }else if (parser.getName().equals(RasterMetaFileTags.WIDTH)){
292
                                                        w = Double.parseDouble(parser.nextText());
293
                                                }else if (parser.getName().equals(RasterMetaFileTags.HEIGHT)){
294
                                                        h = Double.parseDouble(parser.nextText());
295
                                                }
296
                                        }                    
297
                                        break;
298
                         case KXmlParser.END_TAG:
299
                                 if (parser.getName().equals(RasterMetaFileTags.BBOX))
300
                                         end = true;
301
                                break;
302
                        case KXmlParser.TEXT:
303
                                break;
304
                    }
305
                    tag = parser.next();
306
            }
307
                
308
            double[] values = {originX, originY, w, h, pixelSizeX, pixelSizeY, shearX, shearY};
309
                return values;
310
        }
311
        
312
        /**
313
         * Obtiene la informaci?n de georreferenciaci?n asociada a la imagen en un fichero .rmf. Esta 
314
         * georreferenciaci?n tiene la caracteristica de que tiene prioridad sobre la de la imagen.
315
         * Es almacenada en la clase GeoFile en la variable virtualExtent.
316
         * @param file Fichero de metadatos .rmf
317
         */
318
        protected void readGeoInfo(String file){
319
                String rmf = file.substring(0, file.lastIndexOf(".") + 1) + "rmf";
320
                File rmfFile = new File(rmf);
321
                if(!rmfFile.exists())
322
                        return;
323
                
324
                boolean georefOk = false;
325
                
326
                FileReader fr = null;
327
                String v = null;
328
                try {
329
                        fr = new FileReader(rmf);
330
                        KXmlParser parser = new KXmlParser();
331
                        parser.setInput(new FileInputStream(rmf), readFileEncoding(rmf));
332
                        int tag = parser.nextTag();
333
                        if ( parser.getEventType() != KXmlParser.END_DOCUMENT ){                    
334
                                parser.require(KXmlParser.START_TAG, null, RasterMetaFileTags.MAIN_TAG);                            
335
                                while(tag != KXmlParser.END_DOCUMENT) {
336
                                        switch(tag) {
337
                                                case KXmlParser.START_TAG:
338
                                                        if (parser.getName().equals(RasterMetaFileTags.LAYER)) {
339
                                                                int layerListTag = parser.next();
340
                                                                boolean geoRefEnd = false;
341
                                                                while (!geoRefEnd){
342
                                                                        if(parser.getName() != null){
343
                                                                                if (parser.getName().equals(RasterMetaFileTags.PROJ)){
344
                                                                                        //System.out.println("PROJ:"+parser.nextText());
345
                                                                                } else if (parser.getName().equals(RasterMetaFileTags.BBOX)){
346
                                                                                        double[] values = parserExtent(parser);
347
                                                                                        originX = values[0];
348
                                                                                        originY = values[1];
349
                                                                                        w = values[2];
350
                                                                                        h = values[3];
351
                                                                                        pixelSizeX = values[4];
352
                                                                                        pixelSizeY = values[5];
353
                                                                                        shearX = values[6];
354
                                                                                        shearY = values[7];
355
                                                                                        georefOk = true;
356
                                                                                } else if (parser.getName().equals(RasterMetaFileTags.DIM)){
357
                                                                                        boolean DimEnd = false;
358
                                                                                        while (!DimEnd){
359
                                                                                                layerListTag = parser.next();
360
                                                                                                if(parser.getName() != null){        
361
                                                                                                        if (parser.getName().equals(RasterMetaFileTags.PX_WIDTH)){
362
                                                                                                                imageWidth = Double.parseDouble(parser.nextText());
363
                                                                                                        }else if (parser.getName().equals(RasterMetaFileTags.PX_HEIGHT)){
364
                                                                                                                imageHeight = Double.parseDouble(parser.nextText());
365
                                                                                                                DimEnd = true;
366
                                                                                                        }                                                                                                        
367
                                                                                                }
368
                                                                                        }
369
                                                                                        geoRefEnd = true;
370
                                                                                }
371
                                                                        }
372
                                                                        layerListTag = parser.next();
373
                                                                }
374
                                                        }
375
                                                        break;
376
                                                case KXmlParser.END_TAG:                                                        
377
                                                        break;
378
                                                case KXmlParser.TEXT:                                                        
379
                                                        break;
380
                                        }
381
                                        tag = parser.next();
382
                                }
383
                                parser.require(KXmlParser.END_DOCUMENT, null, null);
384
                        }
385
                        
386
                        if(georefOk){
387
                                rmfExists = true;
388
                                
389
                                setExtentTransform(originX, originY, w, h, pixelSizeX, pixelSizeY);
390
                                createExtentsFromRMF(        originX, originY, pixelSizeX, pixelSizeY, 
391
                                                                                imageWidth, imageHeight, shearX, shearY);
392
                        }
393
                        
394
                } catch (FileNotFoundException fnfEx) {
395
                } catch (XmlPullParserException xmlEx) {
396
                        xmlEx.printStackTrace();
397
                } catch (IOException e) {
398
                } 
399
                try{
400
                        if(fr != null)
401
                                fr.close();
402
                }catch(IOException ioEx){
403
                        //No est? abierto el fichero por lo que no hacemos nada
404
                }
405
        }
406

    
407
        /**
408
         * <P>
409
         * Calcula el extent de la imagen a partir del fichero rmf con y sin rotaci?n. El extent con rotaci?n corresponde
410
         * a la variable extent que contiene el extent verdadero marcado por el fichero de georreferenciaci?n .rmf. El extent
411
         * sin rotaci?n requestExtent es utilizado para realizar la petici?n ya que la petici?n al driver no se puede
412
         * hacer con coordenadas rotadas.
413
         * 
414
         * El calculo de la bounding box rotada lo hace con los valores de transformaci?n leidos desde el fichero .rmf.
415
         * </p>
416
         * <P>
417
         * Para el calculo de una esquina aplicamos la formula siguiente:<BR>
418
         * PtoX = originX + pixelSizeX * x + shearX * y;<BR>
419
         * PtoY = originY + shearY * x + pixelSizeY * y;<BR>
420
         * Aplicandolo a las cuatro esquinas sustituimos en cada una de ellas por.
421
         * </P>
422
         * <UL> 
423
         * <LI>Esquina superior izquierda: x = 0; y = 0;</LI>
424
         * <LI>Esquina superior derecha: x = MaxX; y = 0;</LI>
425
         * <LI>Esquina inferior izquierda: x = 0; y = MaxY;</LI>
426
         * <LI>Esquina inferior derecha: x = MaxX; y = MaxY;</LI>
427
         * </UL> 
428
         * <P>
429
         * quedandonos en los cuatro casos:
430
         * </P>
431
         * <UL> 
432
         * <LI>Esquina superior izquierda: originX; originY;</LI>
433
         * <LI>Esquina superior derecha: PtoX = originX + pixelSizeX * x; PtoY = originY + shearY * x;</LI>
434
         * <LI>Esquina inferior izquierda:  PtoX = originX + shearX * y; PtoY = originY + pixelSizeY * y;</LI>
435
         * <LI>Esquina inferior derecha: PtoX = originX + pixelSizeX * x + shearX * y; PtoY = originY + shearY * x + pixelSizeY * y;</LI>
436
         * </UL>
437
         * 
438
         * <P>
439
         * El calculo de la bounding box se realizar? de la misma forma pero anulando los parametros de shearing.
440
         * </P>
441
         * 
442
         * @param originX Coordenada X de origen del raster
443
         * @param originY Coordenada Y de origen del raster
444
         * @param pixelSizeX Tama?o de pixel en X
445
         * @param pixelSizeY Tama?o de pixel en Y
446
         * @param imageWidth Ancho del raster en pixels
447
         * @param imageHeight Alto del raster en pixels
448
         * @param shearX Shearing en X
449
         * @param shearY Shearing en Y
450
         */
451
        private void createExtentsFromRMF(        double originX, double originY, double pixelSizeX, double pixelSizeY, 
452
                                                                                double imageWidth, double imageHeight, double shearX, double shearY){
453
                                
454
                Point2D p1 = new Point2D.Double(originX, originY);
455
                Point2D p2 = new Point2D.Double(originX + shearX * imageHeight, originY + pixelSizeY * imageHeight);
456
                Point2D p3 = new Point2D.Double(originX + pixelSizeX * imageWidth, originY + shearY * imageWidth);
457
                Point2D p4 = new Point2D.Double(originX + pixelSizeX * imageWidth + shearX * imageHeight, originY + pixelSizeY * imageHeight + shearY * imageWidth);
458
                
459
                double minX = Math.min(Math.min(p1.getX(), p2.getX()), Math.min(p3.getX(), p4.getX()));
460
                double minY = Math.min(Math.min(p1.getY(), p2.getY()), Math.min(p3.getY(), p4.getY()));
461
                double maxX = Math.max(Math.max(p1.getX(), p2.getX()), Math.max(p3.getX(), p4.getX()));
462
                double maxY = Math.max(Math.max(p1.getY(), p2.getY()), Math.max(p3.getY(), p4.getY()));
463
                extent = new Extent(minX, minY, maxX, maxY);
464
                requestExtent = new Extent(originX, originY, originX + (pixelSizeX * imageWidth), originY + (pixelSizeY * imageHeight));
465
        }
466
        
467
        /**
468
         * Calcula la transformaci?n que se produce sobre la vista cuando la imagen tiene un fichero .rmf
469
         * asociado. Esta transformaci?n tiene diferencias entre los distintos formatos por lo que debe calcularla
470
         * el driver correspondiente.
471
         * @param originX Origen de la imagen en la coordenada X
472
         * @param originY Origen de la imagen en la coordenada Y
473
         */
474
        abstract public void setExtentTransform(double originX, double originY, double w, double h, double psX, double psY);
475
        
476
        public static PxContour getContour(String fName, String name, IProjection proj) {
477
                PxContour contour = null;
478
                return contour;
479
        }
480
                
481
        /**
482
         * Obtiene el ancho de la imagen
483
         * @return Ancho de la imagen
484
         */
485
        abstract public int getWidth();
486
        
487
        /**
488
         * Obtiene el ancho de la imagen
489
         * @return Ancho de la imagen
490
         */
491
        abstract public int getHeight();
492

    
493
        /**
494
         * Reproyecci?n.
495
         * @param rp        Coordenadas de la transformaci?n
496
         */
497
        abstract public void reProject(ICoordTrans rp);
498

    
499
        /**
500
         * Asigna un nuevo Extent 
501
         * @param e        Extent
502
         */
503
        abstract public void setView(Extent e);
504
        
505
        /**
506
         * Obtiene el extent asignado
507
         * @return        Extent
508
         */
509
        abstract public Extent getView();
510
        
511
        public void setTransparency(boolean t) {
512
                doTransparency = t;
513
                tFilter = new PixelFilter(255);
514
        }
515
        
516
        /**
517
         * Asigna un valor de transparencia
518
         * @param t        Valor de transparencia
519
         */
520
        public void setTransparency(int t ) {
521
                doTransparency = true;
522
                tFilter = new SimplePixelFilter(255 - t);
523
        }
524
        
525
        public boolean getTransparency() { return doTransparency; }
526
        
527
        public void setAlpha(int alpha) {
528
                if (!doTransparency) setTransparency(255 - alpha);
529
                else tFilter.setAlpha(alpha);
530
        }
531
        public int getAlpha() {
532
                if (tFilter == null)
533
                        return 255;
534
                return tFilter.getAlpha();
535
        }
536
        
537
        public void setUpdatable(Component c) { updatable = c; }
538
        
539
        /**
540
         * Actualiza la imagen
541
         * @param width        ancho
542
         * @param height        alto
543
         * @param rp        Reproyecci?n
544
         * @return        img
545
         */
546
        abstract public Image updateImage(int width, int height, ICoordTrans rp);
547

    
548
        /**
549
         * Obtiene el valor del raster en la coordenada que se le pasa.
550
         * El valor ser? Double, Int, Byte, etc. dependiendo del tipo de
551
         * raster.
552
         * @param x        coordenada X
553
         * @param y coordenada Y
554
         * @return
555
         */
556
        abstract public Object getData(int x, int y, int band);
557

    
558
        /**
559
         * Actualiza la/s banda/s especificadas en la imagen.
560
         * @param width                ancho
561
         * @param height        alto
562
         * @param rp                reproyecci?n
563
         * @param img                imagen
564
         * @param flags                que bandas [ RED_BAND | GREEN_BAND | BLUE_BAND ]
565
         * @return                img
566
         * @throws SupersamplingNotSupportedException
567
         */
568
        abstract public Image updateImage(int width, int height, ICoordTrans rp, Image img, int origBand, int destBand)throws SupersamplingNotSupportedException;
569

    
570
        public int getBandCount() { return bandCount; }
571
        
572
        /**
573
         * Asocia un colorBand al rojo, verde o azul.
574
         * @param flag cual (o cuales) de las bandas.
575
         * @param nBand        que colorBand
576
         */
577
        
578
        public void setBand(int flag, int bandNr) {
579
                if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) rBandNr = bandNr;
580
                if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) gBandNr = bandNr;
581
                if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) bBandNr = bandNr;
582
        }
583

    
584
        /**
585
         * Devuelve el colorBand activo en la banda especificada.
586
         * @param flag banda.
587
         */
588
        
589
        public int getBand(int flag) {
590
                if (flag == GeoRasterFile.RED_BAND) return rBandNr;
591
                if (flag == GeoRasterFile.GREEN_BAND) return gBandNr;
592
                if (flag == GeoRasterFile.BLUE_BAND) return bBandNr;
593
                return -1;
594
        }
595
        
596
        /**
597
         * @return Returns the dataType.
598
         */
599
        public int getDataType() {
600
                return dataType;
601
        }
602
        
603
        /**
604
         * @param dataType The dataType to set.
605
         */
606
        public void setDataType(int dataType) {
607
                this.dataType = dataType;
608
        }
609

    
610
        public IObjList getObjects() {
611
                // TODO hay que a?adir el raster a la lista de objetos
612
                IObjList oList = new PxObjList(proj);
613
                return oList;
614
        }
615
        
616
        /**
617
         * Calcula los par?metros de un worl file a partir de las esquinas del raster.
618
         *    1. X pixel size A
619
         *    2. X rotation term D
620
         *    3. Y rotation term B
621
         *    4. Y pixel size E
622
         *    5. X coordinate of upper left corner C
623
         *    6. Y coordinate of upper left corner F
624
         * where the real-world coordinates x',y' can be calculated from
625
         * the image coordinates x,y with the equations
626
         *  x' = Ax + By + C and y' = Dx + Ey + F.
627
         *  The signs of the first 4 parameters depend on the orientation
628
         *  of the image. In the usual case where north is more or less
629
         *  at the top of the image, the X pixel size will be positive
630
         *  and the Y pixel size will be negative. For a south-up image,
631
         *  these signs would be reversed.
632
         * 
633
         * You can calculate the World file parameters yourself based
634
         * on the corner coordinates. The X and Y pixel sizes can be
635
         *  determined simply by dividing the distance between two
636
         *  adjacent corners by the number of columns or rows in the image.
637
         *  The rotation terms are calculated with these equations:
638
         * 
639
         *  # B = (A * number_of_columns + C - lower_right_x') / number_of_rows * -1
640
         *  # D = (E * number_of_rows + F - lower_right_y') / number_of_columns * -1
641
         * 
642
         * @param corner (tl, tr, br, bl)
643
         * @return
644
         */
645
        public static double [] cornersToWorldFile(Point2D [] esq, Dimension size) {
646
                double a=0,b=0,c=0,d=0,e=0,f=0;
647
                double x1 = esq[0].getX(), y1 = esq[0].getY();
648
                double x2 = esq[1].getX(), y2 = esq[1].getY();
649
                double x3 = esq[2].getX(), y3 = esq[2].getY();
650
                double x4 = esq[3].getX(), y4 = esq[3].getY();
651
                // A: X-scale
652
                a = Math.abs( Math.sqrt( (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
653
                      / size.getWidth());
654

    
655
                // E: negative Y-scale
656
                e =  - Math.abs(Math.sqrt((x1-x4)*(x1-x4)+
657
                      (y1-y4)*(y1-y4))/size.getHeight());
658

    
659
                // C, F: upper-left coordinates
660
                c = x1;
661
                f = y1;
662
                
663
                // B & D: rotation parameters
664
                b = (a * size.getWidth() + c - x3 ) / size.getHeight() * -1;
665
                d = (e * size.getHeight() + f - y3 ) / size.getWidth() * -1;
666

    
667
                double [] wf = {a,d,b,e,c,f}; 
668
                return wf;  
669
        }
670
    public static String printWF(String fName, Point2D [] esq, Dimension sz) {
671
            double [] wf = GeoRasterFile.cornersToWorldFile(esq, sz);
672
            System.out.println("wf para "+fName);
673
            System.out.println(esq+"\n"+sz);
674
            String wfData = "";
675
            for (int i=0; i<6; i++)
676
                    wfData += wf[i]+"\n";
677
                System.out.println(wfData);
678
                return wfData;
679
    }
680
    
681
    public static void saveWF(String fName, String data) throws IOException {
682
            FileWriter fw = new FileWriter(fName);
683
            fw.write(data);
684
            fw.flush();
685
            fw.close();
686
    }
687

    
688
        /**
689
         * Cosulta si hay que verificar la relaci?n de aspecto de la imagen, es decir comprueba que el ancho/alto
690
         * pasados a updateImage coinciden con el ancho/alto solicitado en setView a la imagen
691
         * @return true si est? verificando la relaci?n de aspecto. 
692
         */
693
        public boolean mustVerifySize() {
694
                return verifySize;
695
        }
696

    
697
        /**
698
         * Asigna el flag que dice si hay que verificar la relaci?n de aspecto de la imagen, es decir 
699
         * comprueba que el ancho/alto pasados a updateImage coinciden con el ancho/alto solicitado 
700
         * en setView a la imagen.
701
         * @return true si est? verificando la relaci?n de aspecto. 
702
         */
703
        public void setMustVerifySize(boolean verifySize) {
704
                this.verifySize = verifySize;
705
        }
706

    
707
        abstract public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band);
708
        abstract public int getBlockSize();
709
        
710
        /**
711
         * Obtiene el objeto que contiene los metadatos. Este m?todo debe ser redefinido por los
712
         * drivers si necesitan devolver metadatos. 
713
         * @return
714
         */
715
        public Metadata getMetadata(){
716
                return null;
717
        }
718
        
719
        /**
720
         * Asigna un extent temporal que puede coincidir con el de la vista. Esto es 
721
         * util para cargar imagenes sin georreferenciar ya que podemos asignar el extent
722
         * que queramos para ajustarnos a una vista concreta
723
         * @param tempExtent The tempExtent to set.
724
         */
725
        public void setExtent(Extent ext) {
726
                this.extent = ext;
727
        }
728
        
729
        public boolean isGeoreferenced(){
730
                return true;
731
        }
732
        
733
        /**
734
         * M?todo que indica si existe un fichero .rmf asociado al GeoRasterFile.
735
         * @return
736
         */
737
        public boolean rmfExists(){
738
                return this.rmfExists;
739
        }
740
        
741
        /**
742
         * Obtiene los par?metros de la transformaci?n af?n que corresponde con los elementos de
743
         * un fichero tfw.
744
         * <UL> 
745
         * <LI>[1]tama?o de pixel en X</LI>
746
         * <LI>[2]rotaci?n en X</LI>
747
         * <LI>[4]rotaci?n en Y</LI>
748
         * <LI>[5]tama?o de pixel en Y</LI>
749
         * <LI>[0]origen en X</LI>
750
         * <LI>[3]origen en Y</LI>
751
         * </UL>
752
         * Este m?todo debe ser reimplementado por el driver si tiene esta informaci?n. En principio
753
         * Gdal es capaz de proporcionarla de esta forma.
754
         * @return vector de double con los elementos de la transformaci?n af?n.
755
         */
756
        public double[] getTransform(){return null;}
757
}