Statistics
| Revision:

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

History | View | Annotate | Download (30.7 KB)

1 2809 nacho
/*
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 3488 nacho
        private String ext = "";
58 4006 nacho
        private String shortName = "";
59 3488 nacho
60 2809 nacho
        // Polilinea con extent
61 2849 nacho
        public class Contour extends Vector {
62 2809 nacho
                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 3193 nacho
        protected int rBandNr = 1, gBandNr = 2, bBandNr = 3, aBandNr = 4;
87 2809 nacho
        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 3488 nacho
                ext = fName.toLowerCase().substring(fName.lastIndexOf('.')+1);
97 2809 nacho
                if (ext.compareTo("tif") == 0)
98
                        WITH_OVERVIEWS = false;
99
                width = getRasterXSize();
100
                height = getRasterYSize();
101 4160 nacho
                setDataType(this.getRasterBand(1).getRasterDataType());
102
                shortName = getDriverShortName();
103 2809 nacho
                if (true) { //ext.compareTo("sid") == 0) {
104 4160 nacho
                        //String [] metadata = getMetadata();
105 2809 nacho
                        double ox=0D, oy=0D, resx=0D, resy=0D;
106 3084 nacho
                        try{
107 2849 nacho
                                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 4160 nacho
                                //System.out.println("Origin = ("+ox+","+oy+")");
114 2849 nacho
                                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 3084 nacho
                                 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 2849 nacho
                         }
125 2809 nacho
                } 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 5042 nacho
        double currentViewY = 0D;
146
        double viewportScaleX = 0D;
147
        double viewportScaleY = 0D;
148
        double wcWidth = 0D;
149
        double stepX = 0D;
150
        double stepY = 0D;
151 2809 nacho
        int currentOverview = -1;
152
153 3193 nacho
        protected GdalRasterBand bandR = null, bandG = null, bandB = null, bandA = null;
154 2809 nacho
155
156
        /**
157
         * Devuelve la banda actualmente en uso para el color especificado.
158
         * @param color 0=Rojo, 1=Green, 2=Blue.
159
         * @return
160
         */
161
        public GdalRasterBand getCurrentBand(int color) {
162 3193 nacho
                if (color == 0)
163
                        return bandR;
164
                else if (color == 1)
165
                        return bandG;
166 2809 nacho
                return bandB;
167
        }
168
        // Supone rasters no girados
169
        public Point2D worldToRaster(Point2D pt) {
170
                double x = (((double) currentFullWidth)/(esq.maxX-esq.minX))*(pt.getX()-esq.minX);
171
                double y = (((double) currentFullHeight)/(esq.maxY-esq.minY))*(esq.maxY-pt.getY());
172
                Point2D ptRes = new Point2D.Double(x, y);
173
                return ptRes;
174
        }
175
176
        public int setView(double dWorldTLX, double dWorldTLY,
177
            double dWorldBRX, double dWorldBRY,
178
            int nWidth, int nHeight) {
179
                int err = 0;
180
                currentFullWidth = width;
181
                currentFullHeight = height;
182
                Point2D tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
183
                Point2D br = worldToRaster(new Point2D.Double(dWorldBRX, dWorldBRY));
184
                // Calcula cual es la primera l?nea a leer;
185
                currentViewWidth = nWidth;
186
                currentViewHeight = nHeight;
187 5042 nacho
                wcWidth = Math.abs(br.getX() - tl.getX());
188
189 2809 nacho
                currentViewX = tl.getX();
190 5042 nacho
                viewportScaleX = (double) currentViewWidth/(br.getX()-tl.getX());
191
                viewportScaleY = (double) currentViewHeight/(br.getY()-tl.getY());
192
                stepX = 1D/viewportScaleX;
193
                stepY = 1D/viewportScaleY;
194 2809 nacho
                lastReadLine = tl.getY();
195
                try {
196
                        // calcula el overview a usar
197
                        bandR = getRasterBand(1);
198
                        currentOverview = -1;
199
                        if (WITH_OVERVIEWS && bandR.getOverviewCount() > 0) {
200
                                GdalRasterBand ovb = null;
201
                                for (int i=bandR.getOverviewCount()-1; i>0; i--) {
202
                                        ovb = bandR.getOverview(i);
203 5042 nacho
                                        if (ovb.getRasterBandXSize()>getRasterXSize()*viewportScaleX) {
204 2809 nacho
                                                currentOverview = i;
205 5042 nacho
                                    viewportScaleX *= ((double) width/(double) ovb.getRasterBandXSize());
206
                                    stepX = 1D/viewportScaleX;
207 2809 nacho
                                    currentFullWidth = ovb.getRasterBandXSize();
208
                                    currentFullHeight = ovb.getRasterBandYSize();
209
                                    tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
210
                                    currentViewX = tl.getX();
211
                                    lastReadLine = tl.getY();
212
                                    break;
213
                                        }
214
                                }
215
                        }
216
217
                        // Selecciona las bandas y los overviews necesarios
218
                        bandR = getRasterBand(rBandNr);
219
                        setDataType(bandR.getRasterDataType());
220
                        if (this.getRasterCount() > 1) {
221
                                bandG = getRasterBand(gBandNr);
222
                                bandB = getRasterBand(bBandNr);
223 4006 nacho
                                if(this.getRasterCount() == 4 && shortName.equals("PNG"))
224 3193 nacho
                                        bandA = getRasterBand(aBandNr);
225 2809 nacho
                        }
226
                        if (currentOverview > 0) {
227
                                bandR = bandR.getOverview(currentOverview);
228
                            if (this.getRasterCount() > 1) {
229
                                        bandG = bandG.getOverview(currentOverview);
230
                                        bandB = bandB.getOverview(currentOverview);
231 4006 nacho
                                        if(this.getRasterCount() == 4 && shortName.equals("PNG"))
232 3193 nacho
                                                bandA = bandA.getOverview(currentOverview);
233 2809 nacho
                                }
234
                        }
235
236
                        //System.out.println(band.)
237
                } catch (GdalException e) {
238
                        // TODO Auto-generated catch block
239
                        e.printStackTrace();
240
                }
241
242
                System.out.println("GdalFile: TL=("+dWorldTLX+","+dWorldTLY+
243
                        "); BR=("+dWorldBRX+","+dWorldBRY+")\n"+
244 5042 nacho
                        "GdalFile: escala="+viewportScaleX+"; lastReadLine="+lastReadLine+"\n"+
245 2809 nacho
                    "Actual Raster Size="+currentFullWidth+"x"+currentFullHeight+
246
                        "\nDataType="+dataType);
247
                return err;
248
        }
249
250
        int lastY = -1;
251
252
        public void readLine(int[][] line) throws GdalException {
253 5042 nacho
        int w = (int) (Math.ceil(((double)currentViewWidth)*stepX) + 1);
254
        int x = (int) Math.ceil(currentViewX);
255
        int y = (int) Math.ceil(lastReadLine);
256 3193 nacho
        GdalBuffer r = null, g = null, b = null, p = null;
257
        GdalBuffer a = new GdalBuffer();
258
259 2809 nacho
        //if (alpha > 0) a = alpha << 24;
260
        if (x+w > bandR.getRasterBandXSize())
261
                w = bandR.getRasterBandXSize()-x;
262 3193 nacho
263
        if(bandR.getRasterColorTable() != null){
264
                p = bandR.readRasterWithPalette(x, y, w, 1, w, 1, dataType);
265
                a.buffByte = p.buffAPalette;
266
                r = new GdalBuffer();
267
                r.buffByte = p.buffRPalette;
268
                g = new GdalBuffer();
269
                g.buffByte = p.buffGPalette;
270
                b = new GdalBuffer();
271
                b.buffByte = p.buffBPalette;
272
        }else{
273
                a.buffByte = new byte[w];
274
                        r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
275
                        if (bandG != null)
276
                            g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
277
                        if (bandB != null)
278
                            b = bandB.readRaster(x, y, w, 1, w, 1, dataType);
279
        }
280 5042 nacho
281
        lastReadLine += stepY;
282 3193 nacho
283 4160 nacho
                  int i=0;
284 5042 nacho
                  double j = 0D;
285
                  double initOffset =  Math.abs(currentViewX - ((int)currentViewX));
286 2809 nacho
287
                  if (dataType == GDT_CInt16 || dataType == GDT_Int16  || dataType == GDT_UInt16){
288
                          if (g == null){ // Sibgle Band (Typical DEM)
289
                                  for (int k=0; k<4; k++){
290 5042 nacho
                                          for (i=0, j = initOffset; i<currentViewWidth && j<r.getSize(); i++, j+=stepX) {
291 2809 nacho
                                                  if(k<3)
292
                                                          line[i][k] = (r.buffShort[(int) j] & 0xffff);
293
                                                  else
294
                                                          line[i][3] = 0xff;
295
                                          }
296
                              }
297
                          }else { // Multiband
298
                                  //System.err.println("readLine(): Raster 16bits multibanda");
299
                                  GdalBuffer [] bands = {r,g,b};
300
                                  for (int k=0; k<4; k++){
301 5042 nacho
                                      for (i=0, j = initOffset; i<currentViewWidth && j<r.getSize(); i++, j+=stepX){
302 2809 nacho
                                              if(k<3)
303
                                                      line[i][k] = (bands[k].buffShort[(int) j] & 0xffff);
304
                                              else
305
                                                      line[i][3] = 0xff;
306
                                      }
307
                                  }
308
                          }
309 4160 nacho
                  }else if(dataType == GDT_Float32){
310
                          GdalBuffer [] bands = {r,g,b};
311
                        for (int k=0; k<4; k++){
312 5042 nacho
                              for (i=0, j = initOffset; i<currentViewWidth && j<r.getSize(); i++, j+=stepX){
313 4160 nacho
                                      if(k < 3)
314
                                              line[i][k] = (int)bands[0].buffFloat[(int) j];
315
                                      else
316
                                              line[i][3] = 0xff;
317
                              }
318
                        }
319 2809 nacho
                  }
320 4160 nacho
321 2809 nacho
                return;
322
        }
323
324 4160 nacho
        int readLineRGBA(int [] line) throws GdalException {
325 2809 nacho
                int err = 0;
326 4160 nacho
327 5042 nacho
        int w = (int) (Math.ceil(((double)currentViewWidth)*stepX) + 1);
328 2809 nacho
        int x = (int) currentViewX;
329
        int y = (int) lastReadLine;
330 3193 nacho
        GdalBuffer r = null, g = null, b = null, p = null;
331
        GdalBuffer a = new GdalBuffer();
332
333 5042 nacho
        while(y >= bandR.getRasterBandYSize())
334
                y--;
335
336 2809 nacho
        //if (alpha > 0) a = alpha << 24;
337
        if (x+w > bandR.getRasterBandXSize())
338
                w = bandR.getRasterBandXSize()-x;
339 3193 nacho
340
        if(bandR.getRasterColorTable() != null){
341
                p = bandR.readRasterWithPalette(x, y, w, 1, w, 1, dataType);
342
                a.buffByte = p.buffAPalette;
343
                r = new GdalBuffer();
344
                r.buffByte = p.buffRPalette;
345
                g = new GdalBuffer();
346
                g.buffByte = p.buffGPalette;
347
                b = new GdalBuffer();
348
                b.buffByte = p.buffBPalette;
349
        }else{
350 4006 nacho
                if(getRasterCount() == 4 && shortName.equals("PNG")){
351
                        a = bandA.readRaster(x, y, w, 1, w, 1, GDT_Byte);
352
                        r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
353
                            if (bandG != null)
354
                                g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
355
                            if (bandB != null)
356 4088 nacho
                                b = bandB.readRaster(x, y, w, 1, w, 1, dataType);
357 4006 nacho
                }else{
358
                        r = bandR.readRaster(x, y, w, 1, w, 1, dataType);
359
                            if (bandG != null)
360
                                g = bandG.readRaster(x, y, w, 1, w, 1, dataType);
361
                            if (bandB != null)
362
                                b = bandB.readRaster(x, y, w, 1, w, 1, dataType);
363
                            a.buffByte = new byte[w];
364
                            for (int i = 0;i < w;i++)
365
                                    a.buffByte[i] = (byte)255;
366
                }
367 3193 nacho
        }
368 5042 nacho
                  lastReadLine += stepY;
369
370 4160 nacho
                  int i=0;
371 5042 nacho
                  double j =  Math.abs(currentViewX - ((int)currentViewX));
372 2809 nacho
                int alpha = (this.alpha & 0xff) << 24;
373 5042 nacho
                //try{
374 4160 nacho
                  if (dataType == GDT_Byte){
375 2809 nacho
                          if (g != null)
376 5042 nacho
                              for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=stepX) {
377
                                      int jInt = (int)(j);
378
                                      line[i] = (alpha & ((a.buffByte[jInt])& 0xff) << 24) + ((r.buffByte[jInt] & 0xff) << 16) + ((g.buffByte[jInt] & 0xff) << 8) + (b.buffByte[jInt] & 0xff);
379 2809 nacho
                              }
380
                      else
381 5042 nacho
                              for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=stepX) {
382
                                      int jInt = (int)(j);
383
                                      line[i] = (alpha & ((a.buffByte[jInt])& 0xff) << 24) + ((r.buffByte[jInt] & 0xff) << 16) + ((r.buffByte[jInt] & 0xff) << 8) + (r.buffByte[jInt] & 0xff);
384 2809 nacho
                              }
385 4160 nacho
                  }else if (dataType == GDT_CInt16 || dataType == GDT_Int16  || dataType == GDT_UInt16){
386 2809 nacho
                          if (g == null) // Sibgle Band (Typical DEM)
387
                              /*for (i=0, j=0F, i2 = 1; i<currentViewWidth && i2<r.length;
388
                                      i++, j+=step, i2 = (((int) j)*2)+1) {
389
                                      line[i] = a + ((r[i2-1]) << 8) + r[i2];
390
                              }*/
391 5042 nacho
                                    for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=stepX) {
392
                                            int jInt = (int)(j);
393
                                      line[i] = (alpha & ((a.buffByte[jInt])& 0xff) << 24) + r.buffShort[jInt];
394 2809 nacho
                              }
395
                          else { // Multiband
396
                                  // System.err.println("Raster 16bits multibanda");
397 5042 nacho
                              for (i=0; i<currentViewWidth && j<r.getSize(); i++, j+=stepX) {
398
                                      int jInt = (int)(j);
399
                                      line[i] = (alpha & ((a.buffByte[jInt])& 0xff) << 24) | (((r.buffShort[jInt] & 0xfff0) << 12) & 0xff0000 ) |
400
                                                                                                                           (((g.buffShort[jInt] & 0xfff0) << 4 ) & 0xff00 ) |
401
                                                                                                                           (((b.buffShort[jInt] & 0xfff0) >> 4 ) & 0xff );
402 2809 nacho
                              }
403
                          }
404 4160 nacho
                  }
405 5042 nacho
                //}catch(ArrayIndexOutOfBoundsException ex){}
406 2809 nacho
                return err;
407
        }
408 5042 nacho
409 2809 nacho
        /**
410
         * Lee una franja de la imagen.
411
         * @param bandH Altura de la franja
412
         * @param bufH        Altura del buffer
413
         * @param buf        Buffer con la franja (retorno)
414
         * @return
415
         * @throws GdalException
416
         */
417
        public int readBandRGBA(int bandH, int bufH, int [] buf) throws GdalException {
418
                int err = 0;
419 5042 nacho
        int w = (int)(((double)currentViewWidth)*stepX);
420
        int x = (int)(((double)currentViewX)*stepX);
421 2809 nacho
        int y = (int) lastReadLine;
422 5042 nacho
        int h = (int) (((double)bandH)*stepX);
423 2809 nacho
        System.out.println("Leyendo "+y);
424 3193 nacho
        GdalBuffer r = null, g = null, b = null, p = null;
425
        GdalBuffer a = new GdalBuffer();
426
427 2809 nacho
        if (x+w > bandR.getRasterBandXSize())
428
                w = bandR.getRasterBandXSize()-x;
429 3193 nacho
430
        if(bandR.getRasterColorTable() != null){
431
                p = bandR.readRasterWithPalette(x, y, w, h, w, h, GDT_Byte);
432
                a.buffByte = p.buffAPalette;
433
                r = new GdalBuffer();
434
                r.buffByte = p.buffRPalette;
435
                g = new GdalBuffer();
436
                g.buffByte = p.buffGPalette;
437
                b = new GdalBuffer();
438
                b.buffByte = p.buffBPalette;
439
        }else{
440 4006 nacho
                if(getRasterCount() == 4 && shortName.equals("PNG")){
441
                        a = bandA.readRaster(x, y, w, h, w, h, GDT_Byte);
442
                        r = bandR.readRaster(x, y, w, h, w, h, dataType);
443
                            if (bandG != null)
444
                                g = bandG.readRaster(x, y, w, h, w, h, dataType);
445
                            if (bandB != null)
446
                                b = bandB.readRaster(x, y, w, h, w, h, dataType);
447
                }else{
448
                        r = bandR.readRaster(x, y, w, h, w, h, dataType);
449
                            if (bandG != null)
450
                                g = bandG.readRaster(x, y, w, h, w, h, dataType);
451
                            if (bandB != null)
452
                                b = bandB.readRaster(x, y, w, h, w, h, dataType);
453
                            a.buffByte = new byte[w];
454
                            for (int i = 0;i < w*h;i++)
455
                                    a.buffByte[i] = (byte)255;
456
                }
457 3193 nacho
        }
458 5042 nacho
                  lastReadLine += ((double)bandH)*stepY;
459 2809 nacho
460
                  // TODO Acabar de implementarlo
461
                  float k=0F;
462
                int alpha = (this.alpha & 0xff) << 24;
463
                  for (int j=0, t=0; j<bandH; j++) {
464
                          k = j*w; t=j*currentViewWidth;
465 5042 nacho
                          for (int i=0; i<currentViewWidth && k<r.getSize(); i++, k+=stepX) {
466 4088 nacho
                                  buf[t+i] = (alpha & ((a.buffByte[(int)j])& 0xff) << 24) + ((r.buffByte[(int) k]) << 16) + ((g.buffByte[(int) k]) << 8) + b.buffByte[(int) k];
467 2809 nacho
                          }
468
                  }
469 3193 nacho
470 2809 nacho
                return err;
471
472
        }
473
474
        void pintaInfo() {
475
                try {
476
                        //System.out.println("Origin = "+originX+","+originY);
477
                        //System.out.println("Origin = "+this.);
478
                        System.out.println("GeoTransform:");
479
                        GeoTransform trans = getGeoTransform();
480
                        for (int i=0; i<6; i++)
481
                                System.out.println("  param["+i+"]="+trans.adfgeotransform[i]);
482
                        System.out.println("Metadata:");
483
                        String [] metadata = getMetadata();
484
                        for (int i=0; i<metadata.length; i++) {
485
                                System.out.println(metadata[i]);
486
                        }
487
                } catch (GdalException e) {
488 2849 nacho
489 2809 nacho
                }
490
491
        }
492
493
        void pintaPaleta() {
494
        }
495
496
        public int getBlockSize(){
497
                return this.getBlockSize();
498
        }
499
}
500
501
/**
502
 * @author Luis W. Sevilla
503
 */
504
public class GdalFile extends GeoRasterFile {
505 5042 nacho
        public final static int         BAND_HEIGHT = 64;
506
        protected GdalNative                 file = null;
507 2809 nacho
508
        private Extent v = null;
509
510
        static {
511 3257 nacho
                GeoRasterFile.registerExtension("bmp", GdalFile.class);
512 3193 nacho
                GeoRasterFile.registerExtension("gif", GdalFile.class);
513 2809 nacho
                GeoRasterFile.registerExtension("img", GdalFile.class);
514
                GeoRasterFile.registerExtension("tif", GdalFile.class);
515
                GeoRasterFile.registerExtension("tiff", GdalFile.class);
516
                GeoRasterFile.registerExtension("jpg", GdalFile.class);
517
                GeoRasterFile.registerExtension("png", GdalFile.class);
518
        }
519
520
        public GdalFile(IProjection proj, String fName){
521
                super(proj, fName);
522
                extent = new Extent();
523
                try {
524
                        file = new GdalNative(fName);
525 3084 nacho
                        load();
526 2809 nacho
                        showOnOpen();
527
                        bandCount = file.getRasterCount();
528
                        if ( bandCount > 2) {
529
                                setBand(RED_BAND,   0);
530
                                setBand(GREEN_BAND, 1);
531
                                setBand(BLUE_BAND,  2);
532
                        } else
533
                                setBand(RED_BAND|GREEN_BAND|BLUE_BAND, 0);
534
                } catch(Exception e){
535
                          System.out.println("Error en GdalOpen");
536
                          e.printStackTrace();
537
                          file = null;
538
                }
539 4160 nacho
540
                switch(file.getDataType()){
541
                case 1:setDataType(DataBuffer.TYPE_BYTE);break;//GDT_BYTE
542
                case 2://GDT_UInt16
543
                case 3:setDataType(DataBuffer.TYPE_SHORT);break;//GDT_Int16
544
                case 4://GDT_UInt32
545
                case 5:setDataType(DataBuffer.TYPE_INT);break;//GDT_Int32
546
                case 6:setDataType(DataBuffer.TYPE_FLOAT);break;//GDT_Float32
547
                case 7:setDataType(DataBuffer.TYPE_DOUBLE);break;//GDT_Float64
548
                case 8:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CInt16
549
                case 9:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CInt32
550
                case 10:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CFloat32
551
                case 11:setDataType(DataBuffer.TYPE_UNDEFINED);break;//GDT_CFloat64
552
                }
553
554 2809 nacho
        }
555
556 2849 nacho
        /**
557
         * Obtenemos o calculamos el extent de la imagen.
558
         */
559 2809 nacho
        public GeoFile load() {
560 3084 nacho
561
                extent = new Extent(file.esq.minX, file.esq.minY, file.esq.maxX, file.esq.maxY);
562 2849 nacho
563 2809 nacho
                return this;
564
        }
565
566 3084 nacho
        /**
567
         * Cierra el fichero de imagen
568
         */
569 2809 nacho
        public void close() {
570
                try {
571 3257 nacho
                        if(file != null){
572
                                file.close();
573
                                file = null;
574
                        }
575 2809 nacho
                } catch (GdalException e) {
576
                        // TODO Auto-generated catch block
577
                        e.printStackTrace();
578
                }
579
        }
580
581 3084 nacho
        /**
582
         * Asigna a cada banda R,G o B una banda de la imagen
583
         */
584 2809 nacho
        public void setBand(int flag, int bandNr) {
585
                super.setBand(flag, bandNr);
586
                if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) file.rBandNr = bandNr+1;
587
                if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) file.gBandNr = bandNr+1;
588
                if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) file.bBandNr = bandNr+1;
589
        }
590
591 3084 nacho
        /**
592
         * Asigna el extent de la vista actual
593
         */
594
        public void setView(Extent e) {
595
                v = new Extent(e);
596
        }
597
598
        /**
599
         * Obtiene extent de la vista actual
600
         */
601
        public Extent getView() {
602
                return v;
603
        }
604
605
        /**
606
         * Obtiene la anchura del fichero
607
         */
608
        public int getWidth() {
609
                return file.width;
610
        }
611
612
        /**
613
         * Obtiene la altura del fichero
614
         */
615
        public int getHeight() {
616
                return file.height;
617
        }
618 2809 nacho
619
        /* (non-Javadoc)
620
         * @see org.cresques.io.GeoRasterFile#reProject(org.cresques.cts.ICoordTrans)
621
         */
622
        public void reProject(ICoordTrans rp) {
623
                // TODO Auto-generated method stub
624
625
        }
626 3084 nacho
627 2809 nacho
        /* (non-Javadoc)
628
         * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans)
629
         */
630
        public Image updateImage(int width, int height, ICoordTrans rp) {
631
                int line, pRGBArray[] = null;
632
                Image image = null;
633 3084 nacho
634 5042 nacho
                if (mustVerifySize()) {
635
                        // Work out the correct aspect for the setView call.
636
                        double dFileAspect = (double)v.width()/(double)v.height();
637
                        double dWindowAspect = (double)width /(double)height;
638
639
                        if (dFileAspect > dWindowAspect) {
640
                          height =(int)((double)width/dFileAspect);
641
                        } else {
642
                          width = (int)((double)height*dFileAspect);
643
                        }
644 2809 nacho
                }
645
646
                // Set the view
647
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
648
                        width, height);
649
650
                if(width<=0)width=1;
651
                if(height<=0)height=1;
652
653
                image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
654
                //image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
655
                pRGBArray = new int[width/**BAND_HEIGHT*/];
656
                try {
657
                        //int nLin = height % BAND_HEIGHT;
658
                        file.setAlpha(getAlpha());
659
                        setBand(RED_BAND,   rBandNr);
660
                        setBand(GREEN_BAND, gBandNr);
661
                        setBand(BLUE_BAND,  bBandNr);
662
                        for (line=0; line < height; line++) { //+=BAND_HEIGHT) {
663
                                //int bandH = Math.min(BAND_HEIGHT, height-line);
664
                                //file.readBandRGBA(bandH, BAND_HEIGHT, pRGBArray);
665
                                file.readLineRGBA(pRGBArray);
666
                                setRGBLine((BufferedImage) image, 0, line, width, 1/*bandH*/, pRGBArray, 0, width);
667
                        }
668
                } catch (Exception e) {
669
                        // TODO Auto-generated catch block
670
                        e.printStackTrace();
671
                }
672
673
                return image;
674
        }
675
676
        public RasterBuf getRaster(int width, int height, ICoordTrans rp) {
677 4160 nacho
                int line;
678 2809 nacho
                RasterBuf raster = null;
679 5042 nacho
680
                if(mustVerifySize()){
681
                        // Work out the correct aspect for the setView call.
682
                        double dFileAspect = (double)v.width()/(double)v.height();
683
                        double dWindowAspect = (double)width /(double)height;
684
685
                        if (dFileAspect > dWindowAspect) {
686
                          height =(int)((double)width/dFileAspect);
687
                        } else {
688
                          width = (int)((double)height*dFileAspect);
689
                        }
690 2809 nacho
                }
691
692
                // Set the view
693
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
694
                        width, height);
695
696
                raster = new RasterBuf(DataBuffer.TYPE_INT, width, height, 4, new Point(0,0));
697
                try {
698
                        //int nLin = height % BAND_HEIGHT;
699
                        file.setAlpha(getAlpha());
700
                        setBand(RED_BAND,   rBandNr);
701
                        setBand(GREEN_BAND, gBandNr);
702
                        setBand(BLUE_BAND,  bBandNr);
703
                        for (line=0; line < height; line++) { //+=BAND_HEIGHT) {
704
                                file.readLine(raster.getLineInt(line));
705
                        }
706
                } catch (Exception e) {
707
                        // TODO Auto-generated catch block
708
                        e.printStackTrace();
709
                }
710
711
                return raster;
712
        }
713
714
        /**
715
         * Asigna al objeto Image los valores con los dato de la imagen contenidos en el
716
         * vector de enteros.
717
         * @param image        imagen con los datos actuales
718
         * @param startX        inicio de la posici?n en X dentro de la imagen
719
         * @param startY        inicio de la posici?n en X dentro de la imagen
720
         * @param w        Ancho de la imagen
721
         * @param h        Alto de la imagen
722
         * @param rgbArray        vector que contiene la banda que se va a sustituir
723
         * @param offset        desplazamiento
724
         * @param scansize        tama?o de imagen recorrida por cada p
725
         */
726
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray,
727
                         int offset, int scansize) {
728
                image.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
729
        }
730
731
        /**
732
         * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
733
         * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
734
         * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
735
         * banda correspondiente a flags es sustituida por los datos del vector.
736
         * @param image        imagen con los datos actuales
737
         * @param startX        inicio de la posici?n en X dentro de la imagen
738
         * @param startY        inicio de la posici?n en X dentro de la imagen
739
         * @param w        Ancho de la imagen
740
         * @param h        Alto de la imagen
741
         * @param rgbArray        vector que contiene la banda que se va a sustituir
742
         * @param offset        desplazamiento
743
         * @param scansize        tama?o de imagen recorrida por cada paso
744
         * @param flags        banda que se va a sustituir (Ctes de GeoRasterFile)
745
         */
746
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray,
747
                         int offset, int scansize, int flags) {
748
                int [] line = new int[rgbArray.length];
749
                image.getRGB(startX, startY, w, h, line, offset, scansize);
750
                if (flags == GeoRasterFile.RED_BAND)
751
                        for (int i=0; i<line.length; i++)
752
                                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
753
                else if (flags == GeoRasterFile.GREEN_BAND)
754
                        for (int i=0; i<line.length; i++)
755
                                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
756
                else if (flags == GeoRasterFile.BLUE_BAND)
757
                        for (int i=0; i<line.length; i++)
758
                                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
759
                image.setRGB(startX, startY, w, h, line, offset, scansize);
760
        }
761
762
        /**
763
         * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
764
         * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
765
         * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
766
         * banda correspondiente a flags es sustituida por los datos del vector.
767
         * @param image        imagen con los datos actuales
768
         * @param startX        inicio de la posici?n en X dentro de la imagen
769
         * @param startY        inicio de la posici?n en X dentro de la imagen
770
         * @param w        Ancho de la imagen
771
         * @param h        Alto de la imagen
772
         * @param rgbArray        vector que contiene la banda que se va a sustituir
773
         * @param offset        desplazamiento
774
         * @param scansize        tama?o de imagen recorrida por cada paso
775
         * @param origBand        Banda origen del GeoRasterFile
776
         * @param destBandFlag        banda que se va a sustituir (Ctes de GeoRasterFile)
777
         */
778
        protected void setRGBLine(BufferedImage image, int startX, int startY, int w, int h, int[] rgbArray,
779
                         int offset, int scansize, int origBand, int destBandFlag) {
780
                int [] line = new int[rgbArray.length];
781
                image.getRGB(startX, startY, w, h, line, offset, scansize);
782
                if (origBand == 0 && destBandFlag == GeoRasterFile.RED_BAND)
783
                        for (int i=0; i<line.length; i++)
784
                                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
785
                else if (origBand == 1 && destBandFlag == GeoRasterFile.GREEN_BAND)
786
                        for (int i=0; i<line.length; i++)
787
                                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
788
                else if (origBand == 2 && destBandFlag == GeoRasterFile.BLUE_BAND)
789
                        for (int i=0; i<line.length; i++)
790
                                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
791
792
                else if (origBand == 0 && destBandFlag == GeoRasterFile.GREEN_BAND)
793
                        for (int i=0; i<line.length; i++)
794
                                line[i] = (line[i] & 0xffff00ff) | ((rgbArray[i] & 0x00ff0000) >> 8) ;
795
                else if (origBand == 0 && destBandFlag == GeoRasterFile.BLUE_BAND)
796
                        for (int i=0; i<line.length; i++)
797
                                line[i] = (line[i] & 0xffffff00) | ((rgbArray[i] & 0x00ff0000) >> 16);
798
                else if (origBand == 1 && destBandFlag == GeoRasterFile.RED_BAND)
799
                        for (int i=0; i<line.length; i++)
800
                                line[i] = (line[i] & 0xff00ffff) | ((rgbArray[i] & 0x0000ff00) << 8);
801
802
                else if (origBand == 1 && destBandFlag == GeoRasterFile.BLUE_BAND)
803
                        for (int i=0; i<line.length; i++)
804
                                line[i] = (line[i] & 0xffffff00) | ((rgbArray[i] & 0x0000ff00) >> 8);
805
                else if (origBand == 2 && destBandFlag == GeoRasterFile.RED_BAND)
806
                        for (int i=0; i<line.length; i++)
807
                                line[i] = (line[i] & 0xff00ffff) | ((rgbArray[i] & 0x000000ff) << 16);
808
                else if (origBand == 2 && destBandFlag == GeoRasterFile.GREEN_BAND)
809
                        for (int i=0; i<line.length; i++)
810
                                line[i] = (line[i] & 0xffff00ff) | ((rgbArray[i] & 0x000000ff) << 8);
811
                image.setRGB(startX, startY, w, h, line, offset, scansize);
812
        }
813
814
        private void showOnOpen() {
815
                  // Report en la apertura (quitar)
816
                  System.out.println("Fichero GDAL '"+getName()+"' abierto.");
817
                  System.out.println("Version = "+file.version);
818
                  System.out.println("   Size = ("+file.width+","+file.height+")");
819
                  try {
820
                        System.out.println("   NumBands = ("+file.getRasterCount()+")");
821
                } catch (GdalException e) {
822
                        // TODO Auto-generated catch block
823
                        e.printStackTrace();
824
                }
825 2849 nacho
                  //file.pintaInfo();
826 2809 nacho
                  file.pintaPaleta();
827
828
        }
829
830
        /* (non-Javadoc)
831
         * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans, java.awt.Image, int, int)
832
         */
833 5042 nacho
        public Image updateImage(int width, int height, ICoordTrans rp, Image img, int origBand, int destBandFlag)throws SupersamplingNotSupportedException{
834 2809 nacho
                int line, pRGBArray[] = null;
835 5042 nacho
836
                if(mustVerifySize()){
837
                        // Work out the correct aspect for the setView call.
838
                        double dFileAspect = (double)v.width()/(double)v.height();
839
                        double dWindowAspect = (double)width /(double)height;
840
841
                        if (dFileAspect > dWindowAspect) {
842
                          height =(int)((double)width/dFileAspect);
843
                        } else {
844
                          width = (int)((double)height*dFileAspect);
845
                        }
846 2809 nacho
                }
847
848
                // Set the view
849
                file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(),
850
                        width, height);
851
852
                if(width<=0)width=1;
853
                if(height<=0)height=1;
854
855
                pRGBArray = new int[width/**BAND_HEIGHT*/];
856
                try {
857
                        setBand(RED_BAND,   rBandNr);
858
                        setBand(GREEN_BAND, gBandNr);
859
                        setBand(BLUE_BAND,  bBandNr);
860
                        file.setAlpha(getAlpha());
861
                        if(img!=null){
862
                                for (line=0; line < height; line++) {
863
                                        file.readLineRGBA(pRGBArray);
864
                                        setRGBLine((BufferedImage) img, 0, line, width, 1/*bandH*/, pRGBArray, 0, width, origBand, destBandFlag);
865
                                }
866
                                return img;
867
                        }else{
868
                                Image image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
869
                                for (line=0; line < height; line++) {
870
                                        file.readLineRGBA(pRGBArray);
871
                                        setRGBLine((BufferedImage) image, 0, line, width, 1/*bandH*/, pRGBArray, 0, width);
872
                                }
873
                                return image;
874
                        }
875
                } catch (Exception e) {
876
                        // TODO Auto-generated catch block
877
                        e.printStackTrace();
878
                }
879
880
                return img;
881
        }
882
883
        /* (non-Javadoc)
884
         * @see org.cresques.io.GeoRasterFile#getData(int, int, int)
885
         */
886
        public Object getData(int x, int y, int band) {
887
                // TODO Auto-generated method stub
888
                return null;
889
        }
890
891
        /**
892
         * Devuelve los datos de una ventana solicitada
893
         * @param ulX        coordenada X superior izda.
894
         * @param ulY        coordenada Y superior derecha.
895
         * @param sizeX        tama?o en X de la ventana.
896
         * @param sizeY tama?o en Y de la ventana.
897
         * @param band        Banda solicitada.
898
         */
899
        public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band){
900
901
                return null;
902
        }
903
904
        /**
905
         * Obtiene la zona (Norte / Sur)
906
         * @return true si la zona es norte y false si es sur
907
         */
908
909
        public boolean getZone(){
910
911
                return false;
912
        }
913
914
        /**
915
         *Devuelve el n?mero de zona UTM
916
         *@return N?mero de zona
917
         */
918
919
        public int getUTM(){
920
921
                return 0;
922
        }
923
924
        /**
925
         * Obtiene el sistema de coordenadas geograficas
926
         * @return Sistema de coordenadas geogr?ficas
927
         */
928
        public String getGeogCS(){
929
930
                return new String("");
931
        }
932
        /**
933
         * Devuelve el tama?o de bloque
934
         * @return Tama?o de bloque
935
         */
936
        public int getBlockSize(){
937
     //TODO Nacho: Implementar getBlockSize de EcwFile
938
          return file.getBlockSize();
939
        }
940
}
941