Statistics
| Revision:

root / trunk / libraries / libCq CMS for java.old / src / org / cresques / io / GdalFile.java @ 2849

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

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

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

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

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

    
176
                currentViewX = tl.getX();
177
                viewportScale = (double) currentViewWidth/(br.getX()-tl.getX());
178
                step = 1D/viewportScale;
179
                lastReadLine = tl.getY();
180
                try {
181
                        // calcula el overview a usar
182
                        bandR = getRasterBand(1);
183
                        currentOverview = -1;
184
                        if (WITH_OVERVIEWS && bandR.getOverviewCount() > 0) {
185
                                GdalRasterBand ovb = null;
186
                                for (int i=bandR.getOverviewCount()-1; i>0; i--) {              
187
                                        ovb = bandR.getOverview(i);
188
                                        if (ovb.getRasterBandXSize()>getRasterXSize()*viewportScale) {
189
                                                currentOverview = i;
190
                                    viewportScale *= ((double) width/(double) ovb.getRasterBandXSize());
191
                                    step = 1D/viewportScale;
192
                                    currentFullWidth = ovb.getRasterBandXSize();
193
                                    currentFullHeight = ovb.getRasterBandYSize();
194
                                    tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
195
                                    currentViewX = tl.getX();
196
                                    lastReadLine = tl.getY();
197
                                    break;
198
                                        }
199
                                }
200
                        }
201
        
202
                        // Selecciona las bandas y los overviews necesarios
203
                        bandR = getRasterBand(rBandNr);
204
                        setDataType(bandR.getRasterDataType());
205
                        if (this.getRasterCount() > 1) {
206
                                bandG = getRasterBand(gBandNr);
207
                                bandB = getRasterBand(bBandNr);
208
                        }
209
                        if (currentOverview > 0) {
210
                                bandR = bandR.getOverview(currentOverview);
211
                            if (this.getRasterCount() > 1) {
212
                                        bandG = bandG.getOverview(currentOverview);
213
                                        bandB = bandB.getOverview(currentOverview);
214
                                }
215
                        }
216

    
217
                        //System.out.println(band.)
218
                } catch (GdalException e) {
219
                        // TODO Auto-generated catch block
220
                        e.printStackTrace();
221
                }
222

    
223
                System.out.println("GdalFile: TL=("+dWorldTLX+","+dWorldTLY+
224
                        "); BR=("+dWorldBRX+","+dWorldBRY+")\n"+
225
                        "GdalFile: escala="+viewportScale+"; lastReadLine="+lastReadLine+"\n"+
226
                    "Actual Raster Size="+currentFullWidth+"x"+currentFullHeight+
227
                        "\nDataType="+dataType);
228
                return err;
229
        }
230
        
231
        int lastY = -1;
232
        
233
        public void readLine(int[][] line) throws GdalException {
234
                int err = 0;
235
                int nbands = getRasterCount();
236
                GdalRasterBand band = null;
237
        int w = (int)(((double)currentViewWidth)*step);
238
        int x = (int) currentViewX;
239
        int y = (int) lastReadLine;
240
        GdalBuffer r = null, g = null, b = null;
241
        //if (alpha > 0) a = alpha << 24;
242
        if (x+w > bandR.getRasterBandXSize()) 
243
                w = bandR.getRasterBandXSize()-x;
244
                r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
245
                if (bandG != null)
246
                    g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
247
                if (bandB != null)
248
                    b = bandB.readRaster(x, y, w, 1, w, 1, dataType);
249

    
250
                  lastReadLine += step;
251
                  
252
                  int white = Color.BLUE.getRGB(), i2=0, i=0;
253
                  float j =0F;
254
                  
255
                  if (dataType == GDT_CInt16 || dataType == GDT_Int16  || dataType == GDT_UInt16){
256
                          if (g == null){ // Sibgle Band (Typical DEM)
257
                                  for (int k=0; k<4; k++){
258
                                          for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
259
                                                  if(k<3)
260
                                                          line[i][k] = (r.buffShort[(int) j] & 0xffff);
261
                                                  else
262
                                                          line[i][3] = 0xff;
263
                                          }
264
                              }
265
                          }else { // Multiband
266
                                  short px;
267
                                  //System.err.println("readLine(): Raster 16bits multibanda");
268
                                  GdalBuffer [] bands = {r,g,b};
269
                                  for (int k=0; k<4; k++){
270
                                      for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step){
271
                                              if(k<3)
272
                                                      line[i][k] = (bands[k].buffShort[(int) j] & 0xffff);
273
                                              else
274
                                                      line[i][3] = 0xff;
275
                                      }
276
                                  }
277
                          }
278
                  }
279
                return;
280
        }
281
        
282
        public int readLineRGBA(int [] line) throws GdalException {
283
                int err = 0;
284
                int nbands = getRasterCount();
285
                GdalRasterBand band = null;
286
        int w = (int)(((double)currentViewWidth)*step);
287
        int x = (int) currentViewX;
288
        int y = (int) lastReadLine;
289
        GdalBuffer r = null, g = null, b = null;
290
        //if (alpha > 0) a = alpha << 24;
291
        if (x+w > bandR.getRasterBandXSize()) 
292
                w = bandR.getRasterBandXSize()-x;
293
                r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
294
                if (bandG != null)
295
                    g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
296
                if (bandB != null)
297
                    b = bandB.readRaster(x, y, w, 1, w, 1, dataType);
298

    
299
                  lastReadLine += step;
300
                  
301
                  int white = Color.BLUE.getRGB(), i2=0, i=0;
302
                  float j =0F;
303
                int alpha = (this.alpha & 0xff) << 24;
304
                  if (dataType == GDT_Byte)
305
                          if (g != null)
306
                              for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
307
                                      line[i] = alpha + ((r.buffByte[(int) j] & 0xff) << 16) + ((g.buffByte[(int) j] & 0xff) << 8) + (b.buffByte[(int) j] & 0xff);
308
                              }
309
                      else
310
                              for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
311
                                      line[i] = alpha + ((r.buffByte[(int) j] & 0xff) << 16) +
312
                                                ((r.buffByte[(int) j] & 0xff) << 8) + (r.buffByte[(int) j] & 0xff);
313
                              }
314
                  else if (dataType == GDT_CInt16 || dataType == GDT_Int16  || dataType == GDT_UInt16)
315
                          if (g == null) // Sibgle Band (Typical DEM)
316
                              /*for (i=0, j=0F, i2 = 1; i<currentViewWidth && i2<r.length;
317
                                      i++, j+=step, i2 = (((int) j)*2)+1) {
318
                                      line[i] = a + ((r[i2-1]) << 8) + r[i2];
319
                              }*/
320
                                    for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
321
                                      line[i] = alpha + r.buffShort[(int) j];
322
                              }
323
                          else { // Multiband
324
                                  // System.err.println("Raster 16bits multibanda");
325
                              for (i=0, j=0F; i<currentViewWidth && j<r.getSize(); i++, j+=step) {
326
                                      line[i] = alpha | (((r.buffShort[(int) j] & 0xfff0) << 12) & 0xff0000 ) | 
327
                                                                          (((g.buffShort[(int) j] & 0xfff0) << 4 ) & 0xff00 ) |
328
                                                                          (((b.buffShort[(int) j] & 0xfff0) >> 4 ) & 0xff );
329
                              }
330
                          }
331
            //for (int i=0; i<currentViewWidth; i++) line[i] = 128+128*256+128*256*256;
332

    
333
                return err;
334
        }
335
        
336
        /**
337
         * Lee una franja de la imagen.
338
         * @param bandH Altura de la franja
339
         * @param bufH        Altura del buffer
340
         * @param buf        Buffer con la franja (retorno)
341
         * @return
342
         * @throws GdalException
343
         */
344
        public int readBandRGBA(int bandH, int bufH, int [] buf) throws GdalException {
345
                int err = 0;
346
                int nbands = getRasterCount();
347
                GdalRasterBand band = null;
348
        int w = (int)(((double)currentViewWidth)*step);
349
        int x = (int)(((double)currentViewX)*step);
350
        int y = (int) lastReadLine;
351
        int h = (int) (((double)bandH)*step);
352
        System.out.println("Leyendo "+y);
353
                
354
        if (x+w > bandR.getRasterBandXSize()) 
355
                w = bandR.getRasterBandXSize()-x;
356
                GdalBuffer r = bandR.readRaster(x, y, w, h, w, h, GDT_Byte);
357
                GdalBuffer g = bandG.readRaster(x, y, w, h, w, h, GDT_Byte);
358
                GdalBuffer b = bandB.readRaster(x, y, w, h, w, h, GDT_Byte);
359

    
360
                  lastReadLine += ((double)bandH)*step;
361
                  
362
                  // TODO Acabar de implementarlo
363
                  float k=0F;
364
                int alpha = (this.alpha & 0xff) << 24;
365
                  for (int j=0, t=0; j<bandH; j++) {
366
                          k = j*w; t=j*currentViewWidth;
367
                          for (int i=0; i<currentViewWidth && k<r.getSize(); i++, k+=step) {
368
                                  buf[t+i] = alpha + ((r.buffByte[(int) k]) << 16) + ((g.buffByte[(int) k]) << 8) + b.buffByte[(int) k];
369
                          }
370
                  }
371
                //for (int i=0; i<currentViewWidth; i++) line[i] = 128+128*256+128*256*256;
372

    
373
                return err;
374
                
375
        }
376

    
377
        void pintaInfo() {
378
                try {
379
                        //System.out.println("Origin = "+originX+","+originY);
380
                        //System.out.println("Origin = "+this.);
381
                        System.out.println("GeoTransform:");
382
                        GeoTransform trans = getGeoTransform();
383
                        for (int i=0; i<6; i++)
384
                                System.out.println("  param["+i+"]="+trans.adfgeotransform[i]);
385
                        System.out.println("Metadata:");
386
                        String [] metadata = getMetadata();
387
                        for (int i=0; i<metadata.length; i++) {
388
                                System.out.println(metadata[i]);
389
                        }
390
                } catch (GdalException e) {
391
                        
392
                }
393
                
394
        }
395
        
396
        void pintaPaleta() {
397
        }
398
        
399
        public int getBlockSize(){
400
                return this.getBlockSize();
401
        }
402
}
403

    
404
/**
405
 * @author Luis W. Sevilla
406
 */
407
public class GdalFile extends GeoRasterFile {
408
        public final static int BAND_HEIGHT = 64;
409
        protected GdalNative file = null;
410

    
411
        private Extent v = null;
412
        
413
        static {
414
                //GeoRasterFile.registerExtension("sid", GdalFile.class);
415
                GeoRasterFile.registerExtension("img", GdalFile.class);
416
                GeoRasterFile.registerExtension("tif", GdalFile.class);
417
                GeoRasterFile.registerExtension("tiff", GdalFile.class);
418
                GeoRasterFile.registerExtension("jpg", GdalFile.class);
419
                GeoRasterFile.registerExtension("png", GdalFile.class);
420
        }
421
        
422
        public GdalFile(IProjection proj, String fName){
423
                super(proj, fName);
424
                extent = new Extent();
425
                try {
426
                        file = new GdalNative(fName);
427
                        showOnOpen();
428
                        load();
429
                        bandCount = file.getRasterCount(); 
430
                        if ( bandCount > 2) {
431
                                setBand(RED_BAND,   0);
432
                                setBand(GREEN_BAND, 1);
433
                                setBand(BLUE_BAND,  2);
434
                        } else
435
                                setBand(RED_BAND|GREEN_BAND|BLUE_BAND, 0);
436
                } catch(Exception e){
437
                          System.out.println("Error en GdalOpen");
438
                          e.printStackTrace();
439
                          file = null;
440
                }
441
                int dataType = file.getDataType();
442
                  if (dataType == Gdal.GDT_Byte)
443
                          setDataType(DataBuffer.TYPE_BYTE);
444
                  else if (dataType == Gdal.GDT_CInt16 || dataType == Gdal.GDT_Int16)
445
                          setDataType(DataBuffer.TYPE_SHORT);
446
                  else if(dataType == Gdal.GDT_UInt16)
447
                          setDataType(DataBuffer.TYPE_USHORT);
448
        }
449
        
450
        /**
451
         * Obtenemos o calculamos el extent de la imagen.
452
         */
453
        public GeoFile load() {
454
                
455
                //Si el extent temporal tiene alg?n valor usamos este para calcular el de la imagen        
456
                if(this.getTempExtent()!=null){
457
                        extent = this.calcTempExtent(file.width, file.height);
458
                        file.esq = file.new Contour();
459
                          file.esq.add(new Point2D.Double(extent.minX(), extent.minY()));
460
                          file.esq.add(new Point2D.Double(extent.minX()+(extent.maxX() - extent.minX()), extent.minY()));
461
                          file.esq.add(new Point2D.Double(extent.minX(), extent.minY()+(extent.maxY() - extent.minY())));
462
                          file.esq.add(new Point2D.Double(extent.minX()+(extent.maxX() - extent.minX()), extent.minY()+(extent.maxY() - extent.minY())));
463
                }else{ //usamos el de la imagen
464
                        
465
                         //Si la imagen est? georreferenciada obtenemos el extent
466
                        if(file.esq != null)
467
                                extent = new Extent(file.esq.minX, file.esq.minY, file.esq.maxX, file.esq.maxY);
468
                        else{//Si no est? georreferenciada nos inventamos el extent
469
                                extent = new Extent(0, 0, file.width, file.height);
470
                                file.esq = file.new Contour();
471
                                  file.esq.add(new Point2D.Double(0, 0));
472
                                  file.esq.add(new Point2D.Double(file.width, 0));
473
                                  file.esq.add(new Point2D.Double(0, file.height));
474
                                  file.esq.add(new Point2D.Double(file.width, file.height));
475
                        }
476
                }
477
                return this;
478
        }
479
        
480
        public void close() {
481
                try {
482
                        file.close();
483
                } catch (GdalException e) {
484
                        // TODO Auto-generated catch block
485
                        e.printStackTrace();
486
                }
487
        }
488
        
489
        public void setBand(int flag, int bandNr) {
490
                super.setBand(flag, bandNr);
491
                if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) file.rBandNr = bandNr+1;
492
                if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) file.gBandNr = bandNr+1;
493
                if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) file.bBandNr = bandNr+1;
494
        }
495
        public void setView(Extent e) { v = new Extent(e); }
496
        public Extent getView() { return v; }
497
        
498
        public int getWidth() {        return file.width; }
499
        public int getHeight() { return file.height;}
500

    
501
        /* (non-Javadoc)
502
         * @see org.cresques.io.GeoRasterFile#reProject(org.cresques.cts.ICoordTrans)
503
         */
504
        public void reProject(ICoordTrans rp) {
505
                // TODO Auto-generated method stub
506
                
507
        }
508
        /* (non-Javadoc)
509
         * @see org.cresques.io.GeoRasterFile#setTransparency(boolean)
510
         * /
511
        public void setTransparency(boolean t) {
512
                // TODO Auto-generated method stub
513
        }
514
        public void setTransparency(int t) {
515
                // TODO Auto-generated method stub
516
        }*/
517
        /* (non-Javadoc)
518
         * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans)
519
         */
520
        public Image updateImage(int width, int height, ICoordTrans rp) {
521
                double dFileAspect, dWindowAspect;
522
                int line, pRGBArray[] = null;
523
                Image image = null;
524

    
525
                // Work out the correct aspect for the setView call.
526
                dFileAspect = (double)v.width()/(double)v.height();
527
                dWindowAspect = (double)width /(double)height;
528

    
529
                if (dFileAspect > dWindowAspect) {
530
                  height =(int)((double)width/dFileAspect);
531
                } else {
532
                  width = (int)((double)height*dFileAspect);
533
                }
534
                
535
                // Set the view
536
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
537
                        width, height);
538
                
539
                if(width<=0)width=1;
540
                if(height<=0)height=1;
541
                
542
                image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
543
                //image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
544
                pRGBArray = new int[width/**BAND_HEIGHT*/];
545
                try {
546
                        //int nLin = height % BAND_HEIGHT;
547
                        file.setAlpha(getAlpha());
548
                        setBand(RED_BAND,   rBandNr);
549
                        setBand(GREEN_BAND, gBandNr);
550
                        setBand(BLUE_BAND,  bBandNr);
551
                        for (line=0; line < height; line++) { //+=BAND_HEIGHT) {
552
                                //int bandH = Math.min(BAND_HEIGHT, height-line);
553
                                //file.readBandRGBA(bandH, BAND_HEIGHT, pRGBArray);
554
                                file.readLineRGBA(pRGBArray);
555
                                setRGBLine((BufferedImage) image, 0, line, width, 1/*bandH*/, pRGBArray, 0, width);
556
                        }
557
                } catch (Exception e) {
558
                        // TODO Auto-generated catch block
559
                        e.printStackTrace();
560
                }
561
                
562
                return image;
563
        }
564
        
565
        public RasterBuf getRaster(int width, int height, ICoordTrans rp) {
566
                double dFileAspect, dWindowAspect;
567
                int line, pRGBArray[][] = null;
568
                RasterBuf raster = null;
569

    
570
                // Work out the correct aspect for the setView call.
571
                dFileAspect = (double)v.width()/(double)v.height();
572
                dWindowAspect = (double)width /(double)height;
573

    
574
                if (dFileAspect > dWindowAspect) {
575
                  height =(int)((double)width/dFileAspect);
576
                } else {
577
                  width = (int)((double)height*dFileAspect);
578
                }
579
                
580
                // Set the view
581
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
582
                        width, height);
583
                
584
                raster = new RasterBuf(DataBuffer.TYPE_INT, width, height, 4, new Point(0,0));
585
                try {
586
                        //int nLin = height % BAND_HEIGHT;
587
                        file.setAlpha(getAlpha());
588
                        setBand(RED_BAND,   rBandNr);
589
                        setBand(GREEN_BAND, gBandNr);
590
                        setBand(BLUE_BAND,  bBandNr);
591
                        for (line=0; line < height; line++) { //+=BAND_HEIGHT) {
592
                                file.readLine(raster.getLineInt(line));
593
                        }
594
                } catch (Exception e) {
595
                        // TODO Auto-generated catch block
596
                        e.printStackTrace();
597
                }
598
                
599
                return raster;
600
        }
601
        
602
        /**
603
         * Asigna al objeto Image los valores con los dato de la imagen contenidos en el 
604
         * vector de enteros.
605
         * @param image        imagen con los datos actuales
606
         * @param startX        inicio de la posici?n en X dentro de la imagen
607
         * @param startY        inicio de la posici?n en X dentro de la imagen
608
         * @param w        Ancho de la imagen
609
         * @param h        Alto de la imagen
610
         * @param rgbArray        vector que contiene la banda que se va a sustituir
611
         * @param offset        desplazamiento
612
         * @param scansize        tama?o de imagen recorrida por cada p
613
         */
614
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray, 
615
                         int offset, int scansize) {
616
                image.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
617
        }
618
        
619
        /**
620
         * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores 
621
         * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
622
         * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
623
         * banda correspondiente a flags es sustituida por los datos del vector.
624
         * @param image        imagen con los datos actuales
625
         * @param startX        inicio de la posici?n en X dentro de la imagen
626
         * @param startY        inicio de la posici?n en X dentro de la imagen
627
         * @param w        Ancho de la imagen
628
         * @param h        Alto de la imagen
629
         * @param rgbArray        vector que contiene la banda que se va a sustituir
630
         * @param offset        desplazamiento
631
         * @param scansize        tama?o de imagen recorrida por cada paso
632
         * @param flags        banda que se va a sustituir (Ctes de GeoRasterFile)
633
         */
634
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray, 
635
                         int offset, int scansize, int flags) {
636
                int [] line = new int[rgbArray.length]; 
637
                image.getRGB(startX, startY, w, h, line, offset, scansize);
638
                if (flags == GeoRasterFile.RED_BAND)
639
                        for (int i=0; i<line.length; i++)
640
                                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
641
                else if (flags == GeoRasterFile.GREEN_BAND)
642
                        for (int i=0; i<line.length; i++)
643
                                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
644
                else if (flags == GeoRasterFile.BLUE_BAND)
645
                        for (int i=0; i<line.length; i++)
646
                                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
647
                image.setRGB(startX, startY, w, h, line, offset, scansize);
648
        }
649
        
650
        /**
651
         * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores 
652
         * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
653
         * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
654
         * banda correspondiente a flags es sustituida por los datos del vector.
655
         * @param image        imagen con los datos actuales
656
         * @param startX        inicio de la posici?n en X dentro de la imagen
657
         * @param startY        inicio de la posici?n en X dentro de la imagen
658
         * @param w        Ancho de la imagen
659
         * @param h        Alto de la imagen
660
         * @param rgbArray        vector que contiene la banda que se va a sustituir
661
         * @param offset        desplazamiento
662
         * @param scansize        tama?o de imagen recorrida por cada paso
663
         * @param origBand        Banda origen del GeoRasterFile
664
         * @param destBandFlag        banda que se va a sustituir (Ctes de GeoRasterFile)
665
         */
666
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray, 
667
                         int offset, int scansize, int origBand, int destBandFlag) {
668
                int [] line = new int[rgbArray.length]; 
669
                image.getRGB(startX, startY, w, h, line, offset, scansize);
670
                if (origBand == 0 && destBandFlag == GeoRasterFile.RED_BAND)
671
                        for (int i=0; i<line.length; i++)
672
                                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
673
                else if (origBand == 1 && destBandFlag == GeoRasterFile.GREEN_BAND)
674
                        for (int i=0; i<line.length; i++)
675
                                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
676
                else if (origBand == 2 && destBandFlag == GeoRasterFile.BLUE_BAND)
677
                        for (int i=0; i<line.length; i++)
678
                                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
679
                
680
                else if (origBand == 0 && destBandFlag == GeoRasterFile.GREEN_BAND)
681
                        for (int i=0; i<line.length; i++)
682
                                line[i] = (line[i] & 0xffff00ff) | ((rgbArray[i] & 0x00ff0000) >> 8) ;
683
                else if (origBand == 0 && destBandFlag == GeoRasterFile.BLUE_BAND)
684
                        for (int i=0; i<line.length; i++)
685
                                line[i] = (line[i] & 0xffffff00) | ((rgbArray[i] & 0x00ff0000) >> 16);
686
                else if (origBand == 1 && destBandFlag == GeoRasterFile.RED_BAND)
687
                        for (int i=0; i<line.length; i++)
688
                                line[i] = (line[i] & 0xff00ffff) | ((rgbArray[i] & 0x0000ff00) << 8);
689
                
690
                else if (origBand == 1 && destBandFlag == GeoRasterFile.BLUE_BAND)
691
                        for (int i=0; i<line.length; i++)
692
                                line[i] = (line[i] & 0xffffff00) | ((rgbArray[i] & 0x0000ff00) >> 8);
693
                else if (origBand == 2 && destBandFlag == GeoRasterFile.RED_BAND)
694
                        for (int i=0; i<line.length; i++)
695
                                line[i] = (line[i] & 0xff00ffff) | ((rgbArray[i] & 0x000000ff) << 16);
696
                else if (origBand == 2 && destBandFlag == GeoRasterFile.GREEN_BAND)
697
                        for (int i=0; i<line.length; i++)
698
                                line[i] = (line[i] & 0xffff00ff) | ((rgbArray[i] & 0x000000ff) << 8);
699
                image.setRGB(startX, startY, w, h, line, offset, scansize);
700
        }
701
        
702
        private void showOnOpen() {
703
                  // Report en la apertura (quitar)
704
                  System.out.println("Fichero GDAL '"+getName()+"' abierto.");
705
                  System.out.println("Version = "+file.version);
706
                  System.out.println("   Size = ("+file.width+","+file.height+")");
707
                  try {
708
                        System.out.println("   NumBands = ("+file.getRasterCount()+")");
709
                } catch (GdalException e) {
710
                        // TODO Auto-generated catch block
711
                        e.printStackTrace();
712
                }
713
                  //file.pintaInfo();
714
                  file.pintaPaleta();
715

    
716
        }
717

    
718
        /* (non-Javadoc)
719
         * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans, java.awt.Image, int, int)
720
         */
721
        public Image updateImage(int width, int height, ICoordTrans rp, Image img, int origBand, int destBandFlag){
722
                
723
                double dFileAspect, dWindowAspect;
724
                int line, pRGBArray[] = null;
725

    
726
                // Work out the correct aspect for the setView call.
727
                dFileAspect = (double)v.width()/(double)v.height();
728
                dWindowAspect = (double)width /(double)height;
729

    
730
                if (dFileAspect > dWindowAspect) {
731
                  height =(int)((double)width/dFileAspect);
732
                } else {
733
                  width = (int)((double)height*dFileAspect);
734
                }
735
                
736
                // Set the view
737
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
738
                        width, height);
739
                
740
                if(width<=0)width=1;
741
                if(height<=0)height=1;
742
                
743
                pRGBArray = new int[width/**BAND_HEIGHT*/];
744
                try {
745
                        setBand(RED_BAND,   rBandNr);
746
                        setBand(GREEN_BAND, gBandNr);
747
                        setBand(BLUE_BAND,  bBandNr);
748
                        file.setAlpha(getAlpha());
749
                        if(img!=null){
750
                                for (line=0; line < height; line++) { 
751
                                        file.readLineRGBA(pRGBArray);
752
                                        setRGBLine((BufferedImage) img, 0, line, width, 1/*bandH*/, pRGBArray, 0, width, origBand, destBandFlag);
753
                                }
754
                                return img;
755
                        }else{
756
                                Image image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
757
                                for (line=0; line < height; line++) { 
758
                                        file.readLineRGBA(pRGBArray);
759
                                        setRGBLine((BufferedImage) image, 0, line, width, 1/*bandH*/, pRGBArray, 0, width);
760
                                }
761
                                return image;
762
                        }
763
                } catch (Exception e) {
764
                        // TODO Auto-generated catch block
765
                        e.printStackTrace();
766
                }
767
                
768
                return img;
769
        }
770
        
771
        /* (non-Javadoc)
772
         * @see org.cresques.io.GeoRasterFile#getData(int, int, int)
773
         */
774
        public Object getData(int x, int y, int band) {
775
                // TODO Auto-generated method stub
776
                return null;
777
        }
778
        
779
        /**
780
         * Devuelve los datos de una ventana solicitada
781
         * @param ulX        coordenada X superior izda.
782
         * @param ulY        coordenada Y superior derecha.
783
         * @param sizeX        tama?o en X de la ventana.
784
         * @param sizeY tama?o en Y de la ventana.
785
         * @param band        Banda solicitada.
786
         */
787
        public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band){
788
                
789
                return null;
790
        }
791
        
792
        /**
793
         * Obtiene la zona (Norte / Sur)
794
         * @return true si la zona es norte y false si es sur
795
         */
796
        
797
        public boolean getZone(){
798
                
799
                return false;
800
        }
801
        
802
        /**
803
         *Devuelve el n?mero de zona UTM
804
         *@return N?mero de zona 
805
         */
806
        
807
        public int getUTM(){
808
                
809
                return 0;        
810
        }
811
        
812
        /**
813
         * Obtiene el sistema de coordenadas geograficas
814
         * @return Sistema de coordenadas geogr?ficas
815
         */
816
        public String getGeogCS(){
817
                
818
                return new String("");        
819
        }
820
        /**
821
         * Devuelve el tama?o de bloque
822
         * @return Tama?o de bloque
823
         */
824
        public int getBlockSize(){
825
     //TODO Nacho: Implementar getBlockSize de EcwFile        
826
          return file.getBlockSize();
827
        }
828
}
829

    
830