Statistics
| Revision:

svn-gvsig-desktop / tags / Root_v06 / libraries / libCq CMS for java.old / src / org / cresques / io / GdalFile.java @ 4811

History | View | Annotate | Download (30 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.Image;
27
import java.awt.Point;
28
import java.awt.geom.Point2D;
29
import java.awt.image.BufferedImage;
30
import java.awt.image.DataBuffer;
31
import java.io.IOException;
32
import java.util.Vector;
33

    
34
import org.cresques.cts.ICoordTrans;
35
import org.cresques.cts.IProjection;
36
import org.cresques.io.raster.RasterBuf;
37
import org.cresques.px.Extent;
38

    
39
import es.gva.cit.jgdal.Gdal;
40
import es.gva.cit.jgdal.GdalBuffer;
41
import es.gva.cit.jgdal.GdalException;
42
import es.gva.cit.jgdal.GdalRasterBand;
43
import es.gva.cit.jgdal.GeoTransform;
44
/**
45
 * Soporte 'nativo' para ficheros desde GDAL.
46
 * Este conjunto de funcionalidades est? tomado de manera casi literal
47
 * del soporte para ECW de ermapper.<br>
48
 * Probablemente esto deber?a formar parte del JNI que recubre a la
49
 * librer?a en C extraida de gdal.<br>
50
 * Lo pongo aqu? a manera de ejemplo de como atacar un formato binario
51
 * desde Java.<br><br>   
52
 * @author Luis W. Sevilla.
53
 */
54

    
55
class GdalNative extends Gdal {
56
        static boolean WITH_OVERVIEWS = true;
57
        private String ext = "";
58
        private String shortName = "";
59
        
60
        // Polilinea con extent
61
        public class Contour extends Vector {
62
                final private static long serialVersionUID = -3370601314380922368L;
63
                public double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE;
64
                public double maxX = -Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
65
                public Contour() {
66
                        super();
67
                }
68
                public void add(Point2D pt) {
69
                        super.add(pt);
70
                        if (pt.getX() > maxX) maxX = pt.getX();
71
                        if (pt.getX() < minX) minX = pt.getX();
72
                        if (pt.getY() > maxY) maxY = pt.getY();
73
                        if (pt.getY() < minY) minY = pt.getY();
74
                }
75
        }
76
        /**
77
         * Contorno en coordenadas geogr?ficas. (y Extent del raster).
78
         */
79
        
80
        public Contour esq = new Contour();
81
        public int width = 0, height = 0;
82
        public double originX = 0D, originY = 0D;
83
        public String version = "";
84

    
85
        private int alpha = 0;
86
        protected int rBandNr = 1, gBandNr = 2, bBandNr = 3, aBandNr = 4;
87
        private int dataType = GDT_Byte;
88
        
89
        public GdalNative(String fName) throws GdalException, IOException {
90
                super();
91
                init(fName);
92
        }
93
        
94
        private void init(String fName) throws GdalException, IOException {
95
                open(fName,GA_ReadOnly);
96
                ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
97
                if (ext.compareTo("tif") == 0)
98
                        WITH_OVERVIEWS = false;
99
                width = getRasterXSize();
100
                height = getRasterYSize();
101
                setDataType(this.getRasterBand(1).getRasterDataType());
102
                shortName = getDriverShortName();
103
                if (true) { //ext.compareTo("sid") == 0) {
104
                        //String [] metadata = getMetadata();
105
                        double ox=0D, oy=0D, resx=0D, resy=0D;
106
                        try{
107
                                GeoTransform trans = getGeoTransform();
108
                                ox = trans.adfgeotransform[0];
109
                                oy = trans.adfgeotransform[3];
110
                                resx = trans.adfgeotransform[1];
111
                                resy = trans.adfgeotransform[5];
112
                                
113
                                //System.out.println("Origin = ("+ox+","+oy+")");
114
                                System.out.println("Pixel Size = ("+resx+","+resy+")");
115
                                  esq.add(new Point2D.Double(ox, oy));
116
                                  esq.add(new Point2D.Double(ox+resx*width, oy));
117
                                  esq.add(new Point2D.Double(ox, oy+resy*height));
118
                                  esq.add(new Point2D.Double(ox+resx*width, oy+resy*height));
119
                         }catch(GdalException exc){
120
                                 esq.add(new Point2D.Double(0, 0));
121
                                 esq.add(new Point2D.Double(width, 0));
122
                                 esq.add(new Point2D.Double(0, height));
123
                                 esq.add(new Point2D.Double(width, height));
124
                         }
125
                } else  { //version.startsWith("1")) {
126
                          //double [] transParam = getGeoTransform();
127
                          esq.add(new Point2D.Double(0D,height));
128
                          esq.add(new Point2D.Double(0D,0D));
129
                          esq.add(new Point2D.Double(width,0D));
130
                          esq.add(new Point2D.Double(width,height));
131
                  }
132
        }
133
        
134
        public void setAlpha(int a) { alpha = a; }
135
        
136
        public void setDataType(int dt) { dataType = dt; }
137
        public int getDataType() { return dataType; }
138
        
139
        double lastReadLine = -1;
140
        int currentFullWidth = -1;
141
        int currentFullHeight = -1;
142
        int currentViewWidth = -1;
143
        int currentViewHeight = -1;
144
        double currentViewX = 0D;
145
        double viewportScale = 0D;
146
        double step = 0D;
147
        int currentOverview = -1;
148
        
149
        protected GdalRasterBand bandR = null, bandG = null, bandB = null, bandA = null;
150
        
151
        
152
        /**
153
         * Devuelve la banda actualmente en uso para el color especificado.
154
         * @param color 0=Rojo, 1=Green, 2=Blue.
155
         * @return
156
         */
157
        public GdalRasterBand getCurrentBand(int color) {
158
                if (color == 0) 
159
                        return bandR;
160
                else if (color == 1) 
161
                        return bandG;
162
                return bandB;
163
        }
164
        // Supone rasters no girados
165
        public Point2D worldToRaster(Point2D pt) {
166
                double x = (((double) currentFullWidth)/(esq.maxX-esq.minX))*(pt.getX()-esq.minX);
167
                double y = (((double) currentFullHeight)/(esq.maxY-esq.minY))*(esq.maxY-pt.getY());
168
                Point2D ptRes = new Point2D.Double(x, y);
169
                return ptRes;
170
        }
171
        
172
        public int setView(double dWorldTLX, double dWorldTLY,
173
            double dWorldBRX, double dWorldBRY,
174
            int nWidth, int nHeight) {
175
                int err = 0;
176
                currentFullWidth = width;
177
                currentFullHeight = height;
178
                Point2D tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
179
                Point2D br = worldToRaster(new Point2D.Double(dWorldBRX, dWorldBRY));
180
                // Calcula cual es la primera l?nea a leer;
181
                currentViewWidth = nWidth;
182
                currentViewHeight = nHeight;
183

    
184
                currentViewX = tl.getX();
185
                viewportScale = (double) currentViewWidth/(br.getX()-tl.getX());
186
                step = 1D/viewportScale;
187
                lastReadLine = tl.getY();
188
                try {
189
                        // calcula el overview a usar
190
                        bandR = getRasterBand(1);
191
                        currentOverview = -1;
192
                        if (WITH_OVERVIEWS && bandR.getOverviewCount() > 0) {
193
                                GdalRasterBand ovb = null;
194
                                for (int i=bandR.getOverviewCount()-1; i>0; i--) {              
195
                                        ovb = bandR.getOverview(i);
196
                                        if (ovb.getRasterBandXSize()>getRasterXSize()*viewportScale) {
197
                                                currentOverview = i;
198
                                    viewportScale *= ((double) width/(double) ovb.getRasterBandXSize());
199
                                    step = 1D/viewportScale;
200
                                    currentFullWidth = ovb.getRasterBandXSize();
201
                                    currentFullHeight = ovb.getRasterBandYSize();
202
                                    tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
203
                                    currentViewX = tl.getX();
204
                                    lastReadLine = tl.getY();
205
                                    break;
206
                                        }
207
                                }
208
                        }
209
        
210
                        // Selecciona las bandas y los overviews necesarios
211
                        bandR = getRasterBand(rBandNr);
212
                        setDataType(bandR.getRasterDataType());
213
                        if (this.getRasterCount() > 1) {
214
                                bandG = getRasterBand(gBandNr);
215
                                bandB = getRasterBand(bBandNr);
216
                                if(this.getRasterCount() == 4 && shortName.equals("PNG"))
217
                                        bandA = getRasterBand(aBandNr); 
218
                        }
219
                        if (currentOverview > 0) {
220
                                bandR = bandR.getOverview(currentOverview);
221
                            if (this.getRasterCount() > 1) {
222
                                        bandG = bandG.getOverview(currentOverview);
223
                                        bandB = bandB.getOverview(currentOverview);
224
                                        if(this.getRasterCount() == 4 && shortName.equals("PNG"))
225
                                                bandA = bandA.getOverview(currentOverview);
226
                                }
227
                        }
228

    
229
                        //System.out.println(band.)
230
                } catch (GdalException e) {
231
                        // TODO Auto-generated catch block
232
                        e.printStackTrace();
233
                }
234

    
235
                System.out.println("GdalFile: TL=("+dWorldTLX+","+dWorldTLY+
236
                        "); BR=("+dWorldBRX+","+dWorldBRY+")\n"+
237
                        "GdalFile: escala="+viewportScale+"; lastReadLine="+lastReadLine+"\n"+
238
                    "Actual Raster Size="+currentFullWidth+"x"+currentFullHeight+
239
                        "\nDataType="+dataType);
240
                return err;
241
        }
242
        
243
        int lastY = -1;
244
        
245
        public void readLine(int[][] line) throws GdalException {
246
        int w = (int)(((double)currentViewWidth)*step);
247
        int x = (int) currentViewX;
248
        int y = (int) lastReadLine;
249
        GdalBuffer r = null, g = null, b = null, p = null;
250
        GdalBuffer a = new GdalBuffer();
251
        
252
        //if (alpha > 0) a = alpha << 24;
253
        if (x+w > bandR.getRasterBandXSize()) 
254
                w = bandR.getRasterBandXSize()-x;
255
        
256
        if(bandR.getRasterColorTable() != null){
257
                p = bandR.readRasterWithPalette(x, y, w, 1, w, 1, dataType);
258
                a.buffByte = p.buffAPalette;
259
                r = new GdalBuffer();
260
                r.buffByte = p.buffRPalette;
261
                g = new GdalBuffer();
262
                g.buffByte = p.buffGPalette;
263
                b = new GdalBuffer();
264
                b.buffByte = p.buffBPalette;
265
        }else{
266
                a.buffByte = new byte[w];
267
                        r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
268
                        if (bandG != null)
269
                            g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
270
                        if (bandB != null)
271
                            b = bandB.readRaster(x, y, w, 1, w, 1, dataType);
272
        }
273
        
274
                  lastReadLine += step;
275
                  
276
                  int i=0;
277
                  float j =0F;
278
                  
279
                  if (dataType == GDT_CInt16 || dataType == GDT_Int16  || dataType == GDT_UInt16){
280
                          if (g == null){ // Sibgle Band (Typical DEM)
281
                                  for (int k=0; k<4; k++){
282
                                          for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
283
                                                  if(k<3)
284
                                                          line[i][k] = (r.buffShort[(int) j] & 0xffff);
285
                                                  else
286
                                                          line[i][3] = 0xff;
287
                                          }
288
                              }
289
                          }else { // Multiband
290
                                  //System.err.println("readLine(): Raster 16bits multibanda");
291
                                  GdalBuffer [] bands = {r,g,b};
292
                                  for (int k=0; k<4; k++){
293
                                      for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step){
294
                                              if(k<3)
295
                                                      line[i][k] = (bands[k].buffShort[(int) j] & 0xffff);
296
                                              else
297
                                                      line[i][3] = 0xff;
298
                                      }
299
                                  }
300
                          }
301
                  }else if(dataType == GDT_Float32){
302
                          GdalBuffer [] bands = {r,g,b};
303
                        for (int k=0; k<4; k++){
304
                              for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step){
305
                                      //Truncamos el float perdiendo centimetros. Es necesario para visualizar
306
                                      if(k < 3)
307
                                              line[i][k] = (int)bands[0].buffFloat[(int) j];
308
                                      else
309
                                              line[i][3] = 0xff;
310
                              }
311
                        }
312
                  }
313
                  
314
                return;
315
        }
316
        
317
        int readLineRGBA(int [] line) throws GdalException {
318
                int err = 0;
319
                
320
        int w = (int)(((double)currentViewWidth)*step);
321
        int x = (int) currentViewX;
322
        int y = (int) lastReadLine;
323
        GdalBuffer r = null, g = null, b = null, p = null;
324
        GdalBuffer a = new GdalBuffer();
325
        
326
        //if (alpha > 0) a = alpha << 24;
327
        if (x+w > bandR.getRasterBandXSize()) 
328
                w = bandR.getRasterBandXSize()-x;
329
        
330
        if(bandR.getRasterColorTable() != null){
331
                p = bandR.readRasterWithPalette(x, y, w, 1, w, 1, dataType);
332
                a.buffByte = p.buffAPalette;
333
                r = new GdalBuffer();
334
                r.buffByte = p.buffRPalette;
335
                g = new GdalBuffer();
336
                g.buffByte = p.buffGPalette;
337
                b = new GdalBuffer();
338
                b.buffByte = p.buffBPalette;
339
        }else{
340
                if(getRasterCount() == 4 && shortName.equals("PNG")){
341
                        a = bandA.readRaster(x, y, w, 1, w, 1, GDT_Byte);
342
                        r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
343
                            if (bandG != null)
344
                                g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
345
                            if (bandB != null)
346
                                b = bandB.readRaster(x, y, w, 1, w, 1, dataType);        
347
                }else{
348
                        r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
349
                            if (bandG != null)
350
                                g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
351
                            if (bandB != null)
352
                                b = bandB.readRaster(x, y, w, 1, w, 1, dataType);
353
                            a.buffByte = new byte[w];
354
                            for (int i = 0;i < w;i++)
355
                                    a.buffByte[i] = (byte)255;
356
                }
357
        }
358

    
359
                  lastReadLine += step;
360
          
361
                  int i=0;
362
                  float j =0F;
363
                int alpha = (this.alpha & 0xff) << 24;
364
                
365
                  if (dataType == GDT_Byte){
366
                          if (g != null)
367
                              for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
368
                                      line[i] = (alpha & ((a.buffByte[(int)j])& 0xff) << 24) + ((r.buffByte[(int) j] & 0xff) << 16) + ((g.buffByte[(int) j] & 0xff) << 8) + (b.buffByte[(int) j] & 0xff);
369
                              }
370
                      else
371
                              for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
372
                                      line[i] = (alpha & ((a.buffByte[(int)j])& 0xff) << 24) + ((r.buffByte[(int) j] & 0xff) << 16) +
373
                                                ((r.buffByte[(int) j] & 0xff) << 8) + (r.buffByte[(int) j] & 0xff);
374
                              }
375
                  }else if (dataType == GDT_CInt16 || dataType == GDT_Int16  || dataType == GDT_UInt16){
376
                          if (g == null) // Sibgle Band (Typical DEM)
377
                              /*for (i=0, j=0F, i2 = 1; i<currentViewWidth && i2<r.length;
378
                                      i++, j+=step, i2 = (((int) j)*2)+1) {
379
                                      line[i] = a + ((r[i2-1]) << 8) + r[i2];
380
                              }*/
381
                                    for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
382
                                      line[i] = (alpha & ((a.buffByte[(int)j])& 0xff) << 24) + r.buffShort[(int) j];
383
                              }
384
                          else { // Multiband
385
                                  // System.err.println("Raster 16bits multibanda");
386
                              for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
387
                                      line[i] = (alpha & ((a.buffByte[(int)j])& 0xff) << 24) | (((r.buffShort[(int) j] & 0xfff0) << 12) & 0xff0000 ) | 
388
                                                                                                                           (((g.buffShort[(int) j] & 0xfff0) << 4 ) & 0xff00 ) |
389
                                                                                                                           (((b.buffShort[(int) j] & 0xfff0) >> 4 ) & 0xff );
390
                              }
391
                          }
392
                  }
393
            
394
                return err;
395
        }
396
        
397
        /**
398
         * Lee una franja de la imagen.
399
         * @param bandH Altura de la franja
400
         * @param bufH        Altura del buffer
401
         * @param buf        Buffer con la franja (retorno)
402
         * @return
403
         * @throws GdalException
404
         */
405
        public int readBandRGBA(int bandH, int bufH, int [] buf) throws GdalException {
406
                int err = 0;
407
        int w = (int)(((double)currentViewWidth)*step);
408
        int x = (int)(((double)currentViewX)*step);
409
        int y = (int) lastReadLine;
410
        int h = (int) (((double)bandH)*step);
411
        System.out.println("Leyendo "+y);
412
        GdalBuffer r = null, g = null, b = null, p = null;
413
        GdalBuffer a = new GdalBuffer();
414
        
415
        if (x+w > bandR.getRasterBandXSize()) 
416
                w = bandR.getRasterBandXSize()-x;
417
        
418
        if(bandR.getRasterColorTable() != null){
419
                p = bandR.readRasterWithPalette(x, y, w, h, w, h, GDT_Byte);
420
                a.buffByte = p.buffAPalette;
421
                r = new GdalBuffer();
422
                r.buffByte = p.buffRPalette;
423
                g = new GdalBuffer();
424
                g.buffByte = p.buffGPalette;
425
                b = new GdalBuffer();
426
                b.buffByte = p.buffBPalette;
427
        }else{
428
                if(getRasterCount() == 4 && shortName.equals("PNG")){
429
                        a = bandA.readRaster(x, y, w, h, w, h, GDT_Byte);
430
                        r = bandR.readRaster(x, y, w, h, w, h, dataType);
431
                            if (bandG != null)
432
                                g = bandG.readRaster(x, y, w, h, w, h, dataType);
433
                            if (bandB != null)
434
                                b = bandB.readRaster(x, y, w, h, w, h, dataType);
435
                }else{
436
                        r = bandR.readRaster(x, y, w, h, w, h, dataType);
437
                            if (bandG != null)
438
                                g = bandG.readRaster(x, y, w, h, w, h, dataType);
439
                            if (bandB != null)
440
                                b = bandB.readRaster(x, y, w, h, w, h, dataType);
441
                            a.buffByte = new byte[w];
442
                            for (int i = 0;i < w*h;i++)
443
                                    a.buffByte[i] = (byte)255;
444
                }
445
        }
446
                  lastReadLine += ((double)bandH)*step;
447
                  
448
                  // TODO Acabar de implementarlo
449
                  float k=0F;
450
                int alpha = (this.alpha & 0xff) << 24;
451
                  for (int j=0, t=0; j<bandH; j++) {
452
                          k = j*w; t=j*currentViewWidth;
453
                          for (int i=0; i<currentViewWidth && k<r.getSize(); i++, k+=step) {
454
                                  buf[t+i] = (alpha & ((a.buffByte[(int)j])& 0xff) << 24) + ((r.buffByte[(int) k]) << 16) + ((g.buffByte[(int) k]) << 8) + b.buffByte[(int) k];
455
                          }
456
                  }
457
                
458
                return err;
459
                
460
        }
461

    
462
        void pintaInfo() {
463
                try {
464
                        //System.out.println("Origin = "+originX+","+originY);
465
                        //System.out.println("Origin = "+this.);
466
                        System.out.println("GeoTransform:");
467
                        GeoTransform trans = getGeoTransform();
468
                        for (int i=0; i<6; i++)
469
                                System.out.println("  param["+i+"]="+trans.adfgeotransform[i]);
470
                        System.out.println("Metadata:");
471
                        String [] metadata = getMetadata();
472
                        for (int i=0; i<metadata.length; i++) {
473
                                System.out.println(metadata[i]);
474
                        }
475
                } catch (GdalException e) {
476
                        
477
                }
478
                
479
        }
480
        
481
        void pintaPaleta() {
482
        }
483
        
484
        public int getBlockSize(){
485
                return this.getBlockSize();
486
        }
487
}
488

    
489
/**
490
 * @author Luis W. Sevilla
491
 */
492
public class GdalFile extends GeoRasterFile {
493
        public final static int BAND_HEIGHT = 64;
494
        protected GdalNative file = null;
495

    
496
        private Extent v = null;
497
        
498
        static {
499
                GeoRasterFile.registerExtension("bmp", GdalFile.class);
500
                GeoRasterFile.registerExtension("gif", GdalFile.class);
501
                GeoRasterFile.registerExtension("img", GdalFile.class);
502
                GeoRasterFile.registerExtension("tif", GdalFile.class);
503
                GeoRasterFile.registerExtension("tiff", GdalFile.class);
504
                GeoRasterFile.registerExtension("jpg", GdalFile.class);
505
                GeoRasterFile.registerExtension("png", GdalFile.class);
506
        }
507
        
508
        public GdalFile(IProjection proj, String fName){
509
                super(proj, fName);
510
                extent = new Extent();
511
                try {
512
                        file = new GdalNative(fName);
513
                        load();
514
                        showOnOpen();
515
                        bandCount = file.getRasterCount(); 
516
                        if ( bandCount > 2) {
517
                                setBand(RED_BAND,   0);
518
                                setBand(GREEN_BAND, 1);
519
                                setBand(BLUE_BAND,  2);
520
                        } else
521
                                setBand(RED_BAND|GREEN_BAND|BLUE_BAND, 0);
522
                } catch(Exception e){
523
                          System.out.println("Error en GdalOpen");
524
                          e.printStackTrace();
525
                          file = null;
526
                }
527
                
528
                switch(file.getDataType()){
529
                case 1:setDataType(DataBuffer.TYPE_BYTE);break;//GDT_BYTE 
530
                case 2://GDT_UInt16 
531
                case 3:setDataType(DataBuffer.TYPE_SHORT);break;//GDT_Int16        
532
                case 4://GDT_UInt32
533
                case 5:setDataType(DataBuffer.TYPE_INT);break;//GDT_Int32
534
                case 6:setDataType(DataBuffer.TYPE_FLOAT);break;//GDT_Float32
535
                case 7:setDataType(DataBuffer.TYPE_DOUBLE);break;//GDT_Float64
536
                case 8:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CInt16
537
                case 9:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CInt32
538
                case 10:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CFloat32
539
                case 11:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CFloat64
540
                }
541
                
542
        }
543
        
544
        /**
545
         * Obtenemos o calculamos el extent de la imagen.
546
         */
547
        public GeoFile load() {
548
        
549
                extent = new Extent(file.esq.minX, file.esq.minY, file.esq.maxX, file.esq.maxY);        
550
                
551
                return this;
552
        }
553
        
554
        /**
555
         * Cierra el fichero de imagen
556
         */
557
        public void close() {
558
                try {
559
                        if(file != null){
560
                                file.close();
561
                                file = null;
562
                        }
563
                } catch (GdalException e) {
564
                        // TODO Auto-generated catch block
565
                        e.printStackTrace();
566
                }
567
        }
568
        
569
        /**
570
         * Asigna a cada banda R,G o B una banda de la imagen
571
         */
572
        public void setBand(int flag, int bandNr) {
573
                super.setBand(flag, bandNr);
574
                if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) file.rBandNr = bandNr+1;
575
                if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) file.gBandNr = bandNr+1;
576
                if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) file.bBandNr = bandNr+1;
577
        }
578
        
579
        /**
580
         * Asigna el extent de la vista actual
581
         */
582
        public void setView(Extent e) { 
583
                v = new Extent(e); 
584
        }
585
        
586
        /**
587
         * Obtiene extent de la vista actual
588
         */
589
        public Extent getView() { 
590
                return v; 
591
        }
592
        
593
        /**
594
         * Obtiene la anchura del fichero
595
         */
596
        public int getWidth() {        
597
                return file.width; 
598
        }
599
        
600
        /**
601
         * Obtiene la altura del fichero
602
         */
603
        public int getHeight() { 
604
                return file.height;
605
        }
606

    
607
        /* (non-Javadoc)
608
         * @see org.cresques.io.GeoRasterFile#reProject(org.cresques.cts.ICoordTrans)
609
         */
610
        public void reProject(ICoordTrans rp) {
611
                // TODO Auto-generated method stub
612
                
613
        }
614
        
615
        /* (non-Javadoc)
616
         * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans)
617
         */
618
        public Image updateImage(int width, int height, ICoordTrans rp) {
619
                double dFileAspect, dWindowAspect;
620
                int line, pRGBArray[] = null;
621
                Image image = null;
622
                        
623
                // Work out the correct aspect for the setView call.
624
                dFileAspect = (double)v.width()/(double)v.height();
625
                dWindowAspect = (double)width /(double)height;
626

    
627
                if (dFileAspect > dWindowAspect) {
628
                  height =(int)((double)width/dFileAspect);
629
                } else {
630
                  width = (int)((double)height*dFileAspect);
631
                }
632
                
633
                // Set the view
634
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
635
                        width, height);
636
                
637
                if(width<=0)width=1;
638
                if(height<=0)height=1;
639
                
640
                image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
641
                //image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
642
                pRGBArray = new int[width/**BAND_HEIGHT*/];
643
                try {
644
                        //int nLin = height % BAND_HEIGHT;
645
                        file.setAlpha(getAlpha());
646
                        setBand(RED_BAND,   rBandNr);
647
                        setBand(GREEN_BAND, gBandNr);
648
                        setBand(BLUE_BAND,  bBandNr);
649
                        for (line=0; line < height; line++) { //+=BAND_HEIGHT) {
650
                                //int bandH = Math.min(BAND_HEIGHT, height-line);
651
                                //file.readBandRGBA(bandH, BAND_HEIGHT, pRGBArray);
652
                                file.readLineRGBA(pRGBArray);
653
                                setRGBLine((BufferedImage) image, 0, line, width, 1/*bandH*/, pRGBArray, 0, width);
654
                        }
655
                } catch (Exception e) {
656
                        // TODO Auto-generated catch block
657
                        e.printStackTrace();
658
                }
659
                
660
                return image;
661
        }
662
        
663
        public RasterBuf getRaster(int width, int height, ICoordTrans rp) {
664
                double dFileAspect, dWindowAspect;
665
                int line;
666
                RasterBuf raster = null;
667
                                
668
                // Work out the correct aspect for the setView call.
669
                dFileAspect = (double)v.width()/(double)v.height();
670
                dWindowAspect = (double)width /(double)height;
671

    
672
                if (dFileAspect > dWindowAspect) {
673
                  height =(int)((double)width/dFileAspect);
674
                } else {
675
                  width = (int)((double)height*dFileAspect);
676
                }
677
                
678
                // Set the view
679
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
680
                        width, height);
681
                
682
                raster = new RasterBuf(DataBuffer.TYPE_INT, width, height, 4, new Point(0,0));
683
                try {
684
                        //int nLin = height % BAND_HEIGHT;
685
                        file.setAlpha(getAlpha());
686
                        setBand(RED_BAND,   rBandNr);
687
                        setBand(GREEN_BAND, gBandNr);
688
                        setBand(BLUE_BAND,  bBandNr);
689
                        for (line=0; line < height; line++) { //+=BAND_HEIGHT) {
690
                                file.readLine(raster.getLineInt(line));
691
                        }
692
                } catch (Exception e) {
693
                        // TODO Auto-generated catch block
694
                        e.printStackTrace();
695
                }
696
                
697
                return raster;
698
        }
699
        
700
        /**
701
         * Asigna al objeto Image los valores con los dato de la imagen contenidos en el 
702
         * vector de enteros.
703
         * @param image        imagen con los datos actuales
704
         * @param startX        inicio de la posici?n en X dentro de la imagen
705
         * @param startY        inicio de la posici?n en X dentro de la imagen
706
         * @param w        Ancho de la imagen
707
         * @param h        Alto de la imagen
708
         * @param rgbArray        vector que contiene la banda que se va a sustituir
709
         * @param offset        desplazamiento
710
         * @param scansize        tama?o de imagen recorrida por cada p
711
         */
712
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray, 
713
                         int offset, int scansize) {
714
                image.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
715
        }
716
        
717
        /**
718
         * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores 
719
         * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
720
         * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
721
         * banda correspondiente a flags es sustituida por los datos del vector.
722
         * @param image        imagen con los datos actuales
723
         * @param startX        inicio de la posici?n en X dentro de la imagen
724
         * @param startY        inicio de la posici?n en X dentro de la imagen
725
         * @param w        Ancho de la imagen
726
         * @param h        Alto de la imagen
727
         * @param rgbArray        vector que contiene la banda que se va a sustituir
728
         * @param offset        desplazamiento
729
         * @param scansize        tama?o de imagen recorrida por cada paso
730
         * @param flags        banda que se va a sustituir (Ctes de GeoRasterFile)
731
         */
732
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray, 
733
                         int offset, int scansize, int flags) {
734
                int [] line = new int[rgbArray.length]; 
735
                image.getRGB(startX, startY, w, h, line, offset, scansize);
736
                if (flags == GeoRasterFile.RED_BAND)
737
                        for (int i=0; i<line.length; i++)
738
                                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
739
                else if (flags == GeoRasterFile.GREEN_BAND)
740
                        for (int i=0; i<line.length; i++)
741
                                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
742
                else if (flags == GeoRasterFile.BLUE_BAND)
743
                        for (int i=0; i<line.length; i++)
744
                                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
745
                image.setRGB(startX, startY, w, h, line, offset, scansize);
746
        }
747
        
748
        /**
749
         * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores 
750
         * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
751
         * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
752
         * banda correspondiente a flags es sustituida por los datos del vector.
753
         * @param image        imagen con los datos actuales
754
         * @param startX        inicio de la posici?n en X dentro de la imagen
755
         * @param startY        inicio de la posici?n en X dentro de la imagen
756
         * @param w        Ancho de la imagen
757
         * @param h        Alto de la imagen
758
         * @param rgbArray        vector que contiene la banda que se va a sustituir
759
         * @param offset        desplazamiento
760
         * @param scansize        tama?o de imagen recorrida por cada paso
761
         * @param origBand        Banda origen del GeoRasterFile
762
         * @param destBandFlag        banda que se va a sustituir (Ctes de GeoRasterFile)
763
         */
764
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray, 
765
                         int offset, int scansize, int origBand, int destBandFlag) {
766
                int [] line = new int[rgbArray.length]; 
767
                image.getRGB(startX, startY, w, h, line, offset, scansize);
768
                if (origBand == 0 && destBandFlag == GeoRasterFile.RED_BAND)
769
                        for (int i=0; i<line.length; i++)
770
                                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
771
                else if (origBand == 1 && destBandFlag == GeoRasterFile.GREEN_BAND)
772
                        for (int i=0; i<line.length; i++)
773
                                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
774
                else if (origBand == 2 && destBandFlag == GeoRasterFile.BLUE_BAND)
775
                        for (int i=0; i<line.length; i++)
776
                                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
777
                
778
                else if (origBand == 0 && destBandFlag == GeoRasterFile.GREEN_BAND)
779
                        for (int i=0; i<line.length; i++)
780
                                line[i] = (line[i] & 0xffff00ff) | ((rgbArray[i] & 0x00ff0000) >> 8) ;
781
                else if (origBand == 0 && destBandFlag == GeoRasterFile.BLUE_BAND)
782
                        for (int i=0; i<line.length; i++)
783
                                line[i] = (line[i] & 0xffffff00) | ((rgbArray[i] & 0x00ff0000) >> 16);
784
                else if (origBand == 1 && destBandFlag == GeoRasterFile.RED_BAND)
785
                        for (int i=0; i<line.length; i++)
786
                                line[i] = (line[i] & 0xff00ffff) | ((rgbArray[i] & 0x0000ff00) << 8);
787
                
788
                else if (origBand == 1 && destBandFlag == GeoRasterFile.BLUE_BAND)
789
                        for (int i=0; i<line.length; i++)
790
                                line[i] = (line[i] & 0xffffff00) | ((rgbArray[i] & 0x0000ff00) >> 8);
791
                else if (origBand == 2 && destBandFlag == GeoRasterFile.RED_BAND)
792
                        for (int i=0; i<line.length; i++)
793
                                line[i] = (line[i] & 0xff00ffff) | ((rgbArray[i] & 0x000000ff) << 16);
794
                else if (origBand == 2 && destBandFlag == GeoRasterFile.GREEN_BAND)
795
                        for (int i=0; i<line.length; i++)
796
                                line[i] = (line[i] & 0xffff00ff) | ((rgbArray[i] & 0x000000ff) << 8);
797
                image.setRGB(startX, startY, w, h, line, offset, scansize);
798
        }
799
        
800
        private void showOnOpen() {
801
                  // Report en la apertura (quitar)
802
                  System.out.println("Fichero GDAL '"+getName()+"' abierto.");
803
                  System.out.println("Version = "+file.version);
804
                  System.out.println("   Size = ("+file.width+","+file.height+")");
805
                  try {
806
                        System.out.println("   NumBands = ("+file.getRasterCount()+")");
807
                } catch (GdalException e) {
808
                        // TODO Auto-generated catch block
809
                        e.printStackTrace();
810
                }
811
                  //file.pintaInfo();
812
                  file.pintaPaleta();
813

    
814
        }
815

    
816
        /* (non-Javadoc)
817
         * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans, java.awt.Image, int, int)
818
         */
819
        public Image updateImage(int width, int height, ICoordTrans rp, Image img, int origBand, int destBandFlag){
820
                
821
                double dFileAspect, dWindowAspect;
822
                int line, pRGBArray[] = null;
823
                                
824
                // Work out the correct aspect for the setView call.
825
                dFileAspect = (double)v.width()/(double)v.height();
826
                dWindowAspect = (double)width /(double)height;
827

    
828
                if (dFileAspect > dWindowAspect) {
829
                  height =(int)((double)width/dFileAspect);
830
                } else {
831
                  width = (int)((double)height*dFileAspect);
832
                }
833
                
834
                // Set the view
835
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
836
                        width, height);
837
                
838
                if(width<=0)width=1;
839
                if(height<=0)height=1;
840
                
841
                pRGBArray = new int[width/**BAND_HEIGHT*/];
842
                try {
843
                        setBand(RED_BAND,   rBandNr);
844
                        setBand(GREEN_BAND, gBandNr);
845
                        setBand(BLUE_BAND,  bBandNr);
846
                        file.setAlpha(getAlpha());
847
                        if(img!=null){
848
                                for (line=0; line < height; line++) { 
849
                                        file.readLineRGBA(pRGBArray);
850
                                        setRGBLine((BufferedImage) img, 0, line, width, 1/*bandH*/, pRGBArray, 0, width, origBand, destBandFlag);
851
                                }
852
                                return img;
853
                        }else{
854
                                Image image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
855
                                for (line=0; line < height; line++) { 
856
                                        file.readLineRGBA(pRGBArray);
857
                                        setRGBLine((BufferedImage) image, 0, line, width, 1/*bandH*/, pRGBArray, 0, width);
858
                                }
859
                                return image;
860
                        }
861
                } catch (Exception e) {
862
                        // TODO Auto-generated catch block
863
                        e.printStackTrace();
864
                }
865
                
866
                return img;
867
        }
868
        
869
        /* (non-Javadoc)
870
         * @see org.cresques.io.GeoRasterFile#getData(int, int, int)
871
         */
872
        public Object getData(int x, int y, int band) {
873
                // TODO Auto-generated method stub
874
                return null;
875
        }
876
        
877
        /**
878
         * Devuelve los datos de una ventana solicitada
879
         * @param ulX        coordenada X superior izda.
880
         * @param ulY        coordenada Y superior derecha.
881
         * @param sizeX        tama?o en X de la ventana.
882
         * @param sizeY tama?o en Y de la ventana.
883
         * @param band        Banda solicitada.
884
         */
885
        public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band){
886
                
887
                return null;
888
        }
889
        
890
        /**
891
         * Obtiene la zona (Norte / Sur)
892
         * @return true si la zona es norte y false si es sur
893
         */
894
        
895
        public boolean getZone(){
896
                
897
                return false;
898
        }
899
        
900
        /**
901
         *Devuelve el n?mero de zona UTM
902
         *@return N?mero de zona 
903
         */
904
        
905
        public int getUTM(){
906
                
907
                return 0;        
908
        }
909
        
910
        /**
911
         * Obtiene el sistema de coordenadas geograficas
912
         * @return Sistema de coordenadas geogr?ficas
913
         */
914
        public String getGeogCS(){
915
                
916
                return new String("");        
917
        }
918
        /**
919
         * Devuelve el tama?o de bloque
920
         * @return Tama?o de bloque
921
         */
922
        public int getBlockSize(){
923
     //TODO Nacho: Implementar getBlockSize de EcwFile        
924
          return file.getBlockSize();
925
        }
926
}
927

    
928