Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1003 / libraries / libCq CMS for java.old / src / org / cresques / io / MrSidFile.java @ 12271

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

    
32
import org.cresques.cts.ICoordTrans;
33
import org.cresques.cts.IProjection;
34
import org.cresques.io.MrSidNative.Contour;
35
import org.cresques.px.Extent;
36

    
37
import es.gva.cit.jmrsid.LTIColorSpace;
38
import es.gva.cit.jmrsid.LTIDataType;
39
import es.gva.cit.jmrsid.LTIGeoCoord;
40
import es.gva.cit.jmrsid.LTIImageStage;
41
import es.gva.cit.jmrsid.LTIMetadataDatabase;
42
import es.gva.cit.jmrsid.LTIMetadataRecord;
43
import es.gva.cit.jmrsid.LTIPixel;
44
import es.gva.cit.jmrsid.LTIScene;
45
import es.gva.cit.jmrsid.LTISceneBuffer;
46
import es.gva.cit.jmrsid.LTIUtils;
47
import es.gva.cit.jmrsid.MrSIDException;
48
import es.gva.cit.jmrsid.MrSIDImageReader;
49

    
50

    
51
/**
52
 * Soporte para los fichero MrSID de Lizardtech
53
 * @author Nacho Brodin (brodin_ign@gva.es)
54
 */
55
class MrSidNative extends MrSIDImageReader {
56
    static boolean WITH_OVERVIEWS = true;
57

    
58
    /**
59
     * Contorno en coordenadas geogr?ficas. (y Extent del raster).
60
     */
61
    public Contour                                         esq = new Contour();
62
    public int                                                 width = 0;
63
    public int                                                 height = 0;
64
    public double                                         originX = 0D;
65
    public double                                         originY = 0D;
66
    public String                                         version = "";
67
    public LTIMetadataDatabase                 metadata;
68
    public LTIPixel                                 pixel = null;
69
    private int                                         alpha = 0;
70
    protected int                                         rBandNr = 1;
71
    protected int                                         gBandNr = 2;
72
    protected int                                         bBandNr = 3;
73
    protected byte[]                                 bandR;
74
    protected byte[]                                 bandG;
75
    protected byte[]                                 bandB;
76
    private int                                         dataType = LTIDataType.LTI_DATATYPE_UINT8;
77

    
78
    //View
79
    private double                                         zoomoverview = 0.0;
80
    private int                                         eColorSpace;
81
    private int                                         eSampleType;
82
    private int                                         noverviews;
83
    public int                                                 xini;
84
    public int                                                 yini;
85
    /**
86
     * Ancho y alto de la overview
87
     */
88
    public int                                                 anchoOver;
89
    public int                                                 altoOver;
90
    public int                                                 blocksize = 1;
91
    /**
92
     * N?mero de bandas de la imagen
93
     */
94
    public int                                                 nbands;
95
    /**
96
     * N?mero de overview actualmente seleccionada
97
     */
98
    private int                                         currentOverview = -1;
99
    /**
100
     * Posici?n de la esquina superior izquierda en coordenadas pixel
101
     */
102
    private double                                         currentViewY = -1;
103
    private double                                         currentViewX = 0D;
104
    /**
105
     * Ancho y alto de la im?gen (pixeles en pantalla)
106
     */
107
    private int                                         currentViewWidth = -1;
108
    private int                                         currentViewHeight = -1;
109
    /**
110
     * Ancho y alto de la imagen completa en pixeles
111
     */
112
    private int                                         currentFullWidth = -1;
113
    private int                                         currentFullHeight = -1;
114
    /**
115
     * Escala del viewport en X e Y
116
     */
117
    private double                                         viewportScaleX = 0D;
118
    private double                                         viewportScaleY = 0D;
119
    /**
120
     * ?ltimo extent de la ventana seleccionada por el usuario. Este extent corresponde al de la
121
     * imagen, no al del viewport de la vista.
122
     */
123
    private double[]                                currentImageView = new double[4]; 
124

    
125
    /**
126
     * Constructor
127
     * @param fName
128
     * @throws MrSIDException
129
     * @throws IOException
130
     */
131
    public MrSidNative(String fName) throws MrSIDException, IOException {
132
        super(fName);
133
        init(fName);
134
    }
135
    
136
    /**
137
     * Inicializa las variables de instancia con los valores de la imagen
138
     * @param fName
139
     * @throws MrSIDException
140
     * @throws IOException
141
     */
142
    private void init(String fName) throws MrSIDException, IOException {
143
        this.initialize();
144

    
145
        String ext = fName.toLowerCase().substring(fName.lastIndexOf('.') + 1);
146

    
147
        width = this.getWidth();
148
        height = this.getHeight();
149
        eSampleType = this.getDataType();
150
        nbands = this.getNumBands();
151
        eColorSpace = this.getColorSpace();
152
        noverviews = this.getNumLevels();
153

    
154
        metadata = this.getMetadata();
155

    
156
        double ox = 0D;
157
        double oy = 0D;
158
        double resx = 0D;
159
        double resy = 0D;
160

    
161
        LTIGeoCoord geoc = this.getGeoCoord();
162

    
163
        ox = geoc.getX();
164
        oy = geoc.getY();
165
        resx = geoc.getXRes();
166
        resy = geoc.getYRes();
167

    
168
        System.out.println("Origin = (" + ox + "," + oy + ")");
169
        System.out.println("Pixel Size = (" + resx + "," + resy + ")");
170
        esq.add(new Point2D.Double(ox, oy));
171
        esq.add(new Point2D.Double(ox + (resx * width), oy));
172
        esq.add(new Point2D.Double(ox, oy + (resy * height)));
173
        esq.add(new Point2D.Double(ox + (resx * width), oy + (resy * height)));
174

    
175
        blocksize = this.getStripHeight();
176
        System.out.println("StripHeight = (" + blocksize + ")");
177
    }
178

    
179
    /**
180
     * Asigna el valor de Alpha
181
     * @param a        alpha
182
     */
183
    public void setAlpha(int a) {
184
        alpha = a;
185
    }
186

    
187
    /**
188
     * Asigna el tipo de datos
189
     * @param dt        tipo de datos
190
     */
191
    public void setDataType(int dt) {
192
        dataType = dt;
193
    }
194

    
195
    /**
196
     * Obtiene un punto 2D con las coordenadas del raster a partir de uno en coordenadas
197
     * del punto real.
198
     * @param pt        punto en coordenadas del punto real
199
     * @return        punto en coordenadas del raster
200
     */
201
    public Point2D worldToRaster(Point2D pt) {
202
        double x = (((double) currentFullWidth) / (esq.maxX - esq.minX)) * (pt.getX() - esq.minX);
203
        double y = (((double) currentFullHeight) / (esq.maxY - esq.minY)) * (esq.maxY - pt.getY());
204
        Point2D ptRes = new Point2D.Double(x, y);
205
        return ptRes;
206
    }
207

    
208
    /**
209
     * Calcula el overview a usar de la imagen y el viewport a partir del ancho, alto y
210
     * coordenadas del mundo real
211
     * @param dWorldTLX        Coordenada X superior izquierda
212
     * @param dWorldTLY        Coordenada Y superior izquierda
213
     * @param dWorldBRX        Coordenada X inferior derecha
214
     * @param dWorldBRY        Coordenada Y inferior derecha
215
     * @param nWidth        ancho
216
     * @param nHeight        alto
217
     */
218
    public void setView(double dWorldTLX, double dWorldTLY, double dWorldBRX,
219
                        double dWorldBRY, int nWidth, int nHeight) {
220
            currentImageView[0] = dWorldTLX;
221
            currentImageView[1] = dWorldTLY;
222
            currentImageView[2] = dWorldBRX;
223
            currentImageView[3] = dWorldBRY;
224
            
225
        //Ancho y alto de la im?gen en pixeles (pixeles de la overview)
226
        currentFullWidth = width;
227
        currentFullHeight = height;
228

    
229
        //Ventana de la imagen. (en tama?o completo)
230
        //tl->esq sup izda en pixeles
231
        //br->esq inf der en pixeles
232
        Point2D tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
233
        Point2D br = worldToRaster(new Point2D.Double(dWorldBRX, dWorldBRY));
234

    
235
        //Ancho y alto de la im?gen (pixeles en pantalla)
236
        currentViewWidth = nWidth;
237
        currentViewHeight = nHeight;
238

    
239
        //Posici?n de la esquina superior izquierda en coordenadas pixel
240
        currentViewX = tl.getX();
241
        currentViewY = tl.getY();
242

    
243
        //Escala de la vista en X e Y
244
        viewportScaleX = (double) currentViewWidth / (br.getX() - tl.getX());
245
        viewportScaleY = (double) currentViewHeight / (br.getY() - tl.getY());
246
       
247
        try {
248
            // calcula el overview a usar
249
            int[] dims = null;
250
            double zoom = 1.0;
251
            zoomoverview = 1.0;
252
            currentOverview = -1;
253

    
254
            if (WITH_OVERVIEWS && ((noverviews - 1) > 0)) {
255
                for (int i = (noverviews - 1); i > 0; i--) {
256
                    zoom = LTIUtils.levelToMag(i);
257
                    dims = this.getDimsAtMag(zoom);
258

    
259
                    if (dims[0] > (this.getWidth() * viewportScaleX)) {
260
                        currentOverview = i;
261
                        zoomoverview = zoom;
262
                        viewportScaleX /= zoomoverview;
263
                        viewportScaleY /= zoomoverview;
264
                        currentFullWidth = dims[0];
265
                        currentFullHeight = dims[1];
266
                        tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
267
                        currentViewX = tl.getX();
268
                        currentViewY = tl.getY();
269

    
270
                        break;
271
                    }
272
                }
273
            }
274

    
275
            setDataType(eSampleType);
276
        } catch (MrSIDException e) {
277
            e.printStackTrace();
278
        }
279
    }
280

    
281
    /**
282
     * Muestra alguna informaci?n para la depuraci?n
283
     */
284
    void pintaInfo() {
285
        try {
286
            System.out.println("GeoTransform:");
287

    
288
            LTIGeoCoord geoc = this.getGeoCoord();
289

    
290
            System.out.println("  param[0]=" + geoc.getX());
291
            System.out.println("  param[0]=" + geoc.getY());
292
            System.out.println("  param[0]=" + geoc.getXRes());
293
            System.out.println("  param[0]=" + geoc.getYRes());
294
            System.out.println("  param[0]=" + geoc.getXRot());
295
            System.out.println("  param[0]=" + geoc.getYRot());
296
            System.out.println("Metadata:");
297

    
298
            LTIMetadataDatabase metadata = this.getMetadata();
299

    
300
            for (int i = 0; i < metadata.getIndexCount(); i++) {
301
                LTIMetadataRecord rec = null;
302
                rec = metadata.getDataByIndex(i);
303
                System.out.println(rec.getTagName());
304

    
305
                if (rec.isScalar()) {
306
                    System.out.println(rec.getScalarData());
307
                } else if (rec.isVector()) {
308
                    String[] s = rec.getVectorData();
309

    
310
                    for (int j = 0; j < s.length; j++)
311
                        System.out.println("V" + j + "->" + s[j]);
312
                } else if (rec.isArray()) {
313
                    String[] s = rec.getArrayData();
314

    
315
                    for (int j = 0; j < s.length; j++)
316
                        System.out.println("A" + j + "->" + s[j]);
317
                } else {
318
                    System.out.println("");
319
                }
320
            }
321
        } catch (MrSIDException e) {
322
            // TODO Auto-generated catch block
323
            e.printStackTrace();
324
        }
325
    }
326

    
327
    void pintaPaleta() {
328
    }
329

    
330
    public LTISceneBuffer readBuffer(int x, int y, int SceneWidth, int SceneHeight)throws MrSIDException{
331
            LTISceneBuffer buffer = null;
332
            LTIScene scene = new LTIScene(x, y, SceneWidth, SceneHeight, zoomoverview);
333
            buffer = new LTISceneBuffer(pixel, SceneWidth, SceneHeight, true);
334
            ((LTIImageStage) this).read(scene, buffer);
335
            return buffer;
336
    }
337
    
338
    /**
339
     * Lee la escena de la imagen correspondiente a la vista seleccionada con
340
     * currentView a trav?s de la libreria de MrSid. Esta escena es cargada sobre
341
     * un buffer y asignada al par?metro de salida.
342
     * @param line        Escena leida
343
     * @throws MrSIDException Lanzada si ocurre un error en la lectura de la escena
344
     */
345
    public void readScene(int[] line) throws MrSIDException {
346
            //Posici?n de inicio de la escena en entero para la petici?n a la libreria
347
        int x = (int) Math.floor(currentViewX);
348
        int y = (int) Math.floor(currentViewY);
349
        //Ancho y alto de la escena en pixeles
350
        int SceneWidth = 0;
351
        int SceneHeight = 0;
352

    
353
        try {
354
                        SceneWidth = (int) Math.ceil((((double) currentViewWidth) / viewportScaleX) + 1);
355
                        if (SceneWidth > currentFullWidth)
356
                                SceneWidth = currentFullWidth;
357
                        SceneHeight = (int) Math.ceil((((double) currentViewHeight) / viewportScaleY) + 1);
358
                    if (SceneHeight > currentFullHeight)
359
                               SceneHeight = currentFullHeight;
360
          
361
            if (SceneWidth == 0) 
362
                SceneWidth = 1;
363
           
364
            if (SceneHeight == 0)
365
                SceneHeight = 1;
366
            
367
            if (pixel == null)
368
                pixel = new LTIPixel(eColorSpace, nbands, eSampleType);
369
            
370
            LTISceneBuffer buffer = null;
371
            
372
            boolean  sizeOk = false;
373
                        while (!sizeOk){
374
                                sizeOk = true;
375
                    try {
376
                            buffer = readBuffer(x, y, SceneWidth, SceneHeight);
377
                    } catch (MrSIDException ex) {
378
                            SceneWidth-- ;
379
                            try{
380
                                    buffer = readBuffer(x, y, SceneWidth, SceneHeight);
381
                            } catch (MrSIDException ex1) {
382
                                    SceneWidth++;
383
                                    SceneHeight--;
384
                                try{
385
                                        buffer = readBuffer(x, y, SceneWidth, SceneHeight);
386
                                } catch (MrSIDException ex2) {
387
                                        SceneWidth-- ;
388
                                    try{
389
                                            buffer = readBuffer(x, y, SceneWidth, SceneHeight);
390
                                    } catch (MrSIDException ex3) {
391
                                            sizeOk = false;
392
                                    }
393
                                }
394
                            }
395
                    }
396
                        }
397
            
398
                                    
399
            if ((dataType == LTIDataType.LTI_DATATYPE_UINT8) ||
400
                    (dataType == LTIDataType.LTI_DATATYPE_SINT8) ||
401
                    (dataType == LTIDataType.LTI_DATATYPE_SINT16) ||
402
                    (dataType == LTIDataType.LTI_DATATYPE_SINT32) ||
403
                    (dataType == LTIDataType.LTI_DATATYPE_UINT16) ||
404
                    (dataType == LTIDataType.LTI_DATATYPE_UINT32)) {
405
                int kd;
406
                int k;
407
                double scaleX = 1 / viewportScaleX;
408
                double scaleY = 1 / viewportScaleY;
409
                int alpha = (this.alpha & 0xff) << 24;
410
                             
411
                if (rBandNr == 1) {
412
                    bandR = buffer.buf1;
413
                } else if (rBandNr == 2) {
414
                    bandR = buffer.buf2;
415
                } else if (rBandNr == 3) {
416
                    bandR = buffer.buf3;
417
                }
418

    
419
                if (gBandNr == 1) {
420
                    bandG = buffer.buf1;
421
                } else if (gBandNr == 2) {
422
                    bandG = buffer.buf2;
423
                } else if (gBandNr == 3) {
424
                    bandG = buffer.buf3;
425
                }
426

    
427
                if (bBandNr == 1) {
428
                    bandB = buffer.buf1;
429
                } else if (bBandNr == 2) {
430
                    bandB = buffer.buf2;
431
                } else if (bBandNr == 3) {
432
                    bandB = buffer.buf3;
433
                }
434
                
435
                //Desplazamiento para la X y la Y leidas. Estas tienen efecto cuando un pixel no empieza a visualizarse
436
                //justo en su esquina superior izquierda y tiene que ser cortado en la visualizaci?n.
437
                double offsetX = Math.abs(currentViewX - ((int)currentViewX));
438
                double offsetY = Math.abs(currentViewY - ((int)currentViewY));
439
                for (int y1 = 0; y1 < currentViewHeight; y1++){
440
                   for (int x1 = 0; x1 < currentViewWidth; x1++) {
441
                      kd = (y1 * currentViewWidth) + x1;
442
                      k = (((int) ((y1 * scaleY) + offsetY)) * SceneWidth) + 
443
                                      (int) ((x1 * scaleX) + offsetX);
444

    
445
                      try {
446
                            line[kd] = alpha + ((0xff & bandR[k]) << 16) + ((0xff & bandG[k]) << 8) + (0xff & bandB[k]);
447
                      } catch (java.lang.ArrayIndexOutOfBoundsException e) {
448
                      }
449
                   }
450
                }
451
            }
452
            
453
            buffer = null;
454
        } catch (MrSIDException e) {
455
            e.printStackTrace();
456
        }
457
    }
458

    
459
    /**
460
     * Lee una ventana de la imagen y devuelve un buffer de bytes
461
     * @param ulX        Coordenada X de la esquina superior izquierda
462
     * @param ulY        Coordenada Y de la esquina superior izquierda
463
     * @param sizeX        Tama?o X de la imagen
464
     * @param sizeY        Tama?o Y de la image
465
     * @param band        N?mero de bandas
466
     * @return        buffer con la ventana leida
467
     * @throws MrSIDException
468
     */
469
    public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band)
470
                     throws MrSIDException {
471
        if (pixel == null) {
472
            pixel = new LTIPixel(eColorSpace, nbands, eSampleType);
473
        }
474

    
475
        LTIScene scene = new LTIScene(ulX, ulY, sizeX, sizeY, 1.0);
476
        LTISceneBuffer buffer = new LTISceneBuffer(pixel, sizeX, sizeY, true);
477
        ((LTIImageStage) this).read(scene, buffer);
478

    
479
        if (band == 1) {
480
            return buffer.buf1;
481
        } else if (band == 2) {
482
            return buffer.buf2;
483
        } else if (band == 3) {
484
            return buffer.buf3;
485
        }
486

    
487
        return null;
488
    }
489

    
490
    // Polilinea con extent
491
    class Contour extends Vector {
492
        final private static long serialVersionUID = -3370601314380922368L;
493
        public double minX = Double.MAX_VALUE;
494
        public double minY = Double.MAX_VALUE;
495
        public double maxX = -Double.MAX_VALUE;
496
        public double maxY = -Double.MAX_VALUE;
497

    
498
        public Contour() {
499
            super();
500
        }
501

    
502
        public void add(Point2D pt) {
503
            super.add(pt);
504

    
505
            if (pt.getX() > maxX) {
506
                maxX = pt.getX();
507
            }
508

    
509
            if (pt.getX() < minX) {
510
                minX = pt.getX();
511
            }
512

    
513
            if (pt.getY() > maxY) {
514
                maxY = pt.getY();
515
            }
516

    
517
            if (pt.getY() < minY) {
518
                minY = pt.getY();
519
            }
520
        }
521
    }
522
}
523

    
524

    
525
/**
526
 * @author Nacho Brodin <brodin_ign@gva.es>
527
 *
528
 * Clase encargada del acceso a los datos y repintado de imagenes MrSID. Estos
529
 * son registrados con la extensi?n sid
530
 */
531
public class MrSidFile extends GeoRasterFile {
532
    public final static int BAND_HEIGHT = 64;
533

    
534
    static {
535
        GeoRasterFile.registerExtension("sid", MrSidFile.class);
536
    }
537

    
538
    protected MrSidNative file = null;
539
    private Extent v = null;
540

    
541
    /**
542
     * Contructor. Abre el fichero mrsid
543
     * @param proj        Proyecci?n
544
     * @param fName        Nombre del fichero mrsid
545
     */
546
    public MrSidFile(IProjection proj, String fName) {
547
        super(proj, fName);
548
        
549
        extent = new Extent();
550

    
551
        try {
552
            file = new MrSidNative(fName);
553
            showOnOpen();
554
            load();
555
            bandCount = file.nbands;
556

    
557
            if (bandCount > 2) {
558
                setBand(RED_BAND, 0);
559
                setBand(GREEN_BAND, 1);
560
                setBand(BLUE_BAND, 2);
561
            } else {
562
                setBand(RED_BAND | GREEN_BAND | BLUE_BAND, 0);
563
            }
564
        } catch (Exception e) {
565
            System.out.println("Error en constructor de MrSID");
566
            e.printStackTrace();
567
            file = null;
568
        }
569
    }
570

    
571
        /**
572
         * Obtenemos o calculamos el extent de la imagen.
573
         */
574
    public GeoFile load() {
575
            
576
                   extent = new Extent(file.esq.minX, file.esq.minY, file.esq.maxX, file.esq.maxY);
577
                   requestExtent = extent;
578
            
579
            /*if((this.assignedExtent == GeoRasterFile.IMAGE_EXTENT || this.assignedExtent == GeoRasterFile.ORDER ) 
580
                    && file !=null        && file.esq != null){
581
                    extent = new Extent(file.esq.minX, file.esq.minY, file.esq.maxX, file.esq.maxY);
582
                    return this;
583
            }
584
            
585
            if((this.assignedExtent == GeoRasterFile.ASSIGNED_EXTENT || this.assignedExtent == GeoRasterFile.ORDER ) 
586
                    && this.getTempExtent() != null){
587
        
588
                extent = this.getTempExtent();
589
                        file.esq = file.new Contour();
590
                          file.esq.add(new Point2D.Double(extent.minX(), extent.minY()));
591
                          file.esq.add(new Point2D.Double(extent.minX()+(extent.maxX() - extent.minX()), extent.minY()));
592
                          file.esq.add(new Point2D.Double(extent.minX(), extent.minY()+(extent.maxY() - extent.minY())));
593
                          file.esq.add(new Point2D.Double(extent.minX()+(extent.maxX() - extent.minX()), extent.minY()+(extent.maxY() - extent.minY())));
594
        }*/ 
595
        
596
        return this;
597
    }
598

    
599
    /**
600
     * Libera el objeto que ha abierto el fichero
601
     */
602
    public void close() {
603
            if(file != null){
604
                    file.close();
605
                    file = null;
606
            }
607
    }
608

    
609
    /**
610
     * Asigna una banda R, G o B
611
     */
612
    public void setBand(int flag, int bandNr) {
613
        super.setBand(flag, bandNr);
614

    
615
        if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) {
616
            file.rBandNr = bandNr + 1;
617
        }
618

    
619
        if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) {
620
            file.gBandNr = bandNr + 1;
621
        }
622

    
623
        if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) {
624
            file.bBandNr = bandNr + 1;
625
        }
626
    }
627

    
628
    /**
629
     * Asigna el extent de la vista
630
     */
631
    public void setView(Extent e) {
632
        v = new Extent(e);
633
    }
634

    
635
    /**
636
     * Obtiene el Extent de la vista
637
     */
638
    public Extent getView() {
639
        return v;
640
    }
641

    
642
    /**
643
     * Obtiene el ancho de la imagen
644
     */
645
    public int getWidth() {
646
        return file.width;
647
    }
648

    
649
    /**
650
     * Obtiene el alto de la imagen
651
     */
652
    public int getHeight() {
653
        return file.height;
654
    }
655

    
656
    public void reProject(ICoordTrans rp) {
657
        // TODO Auto-generated method stub        
658
    }
659

    
660
    /**
661
     * Actualiza la imagen. Se encarga de llamar a la funci?n que calcula la vista
662
     * y luego a la que lee la escena sobre un buffer. Vuelca la informaci?n obtenida
663
     * sobre el Image que la visualiza.
664
     */
665
    public Image updateImage(int width, int height, ICoordTrans rp) {
666
        int line;
667
        int[] pRGBArray = null;
668
        Image image = null;
669
        
670
        if(mustVerifySize()){
671
                // Work out the correct aspect for the setView call.
672
                double dFileAspect = (double) v.width() / (double) v.height();
673
                double dWindowAspect = (double) width / (double) height;
674
        
675
                if (dFileAspect > dWindowAspect) {
676
                    height = (int) ((double) width / dFileAspect);
677
                } else {
678
                    width = (int) ((double) height * dFileAspect);
679
                }
680
        }
681
        
682
        // Set the view
683
        file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(), width, height);
684

    
685
        //Impedimos que los valores de ancho y alto de la im?gen sean menores que 1
686
        if (width <= 0) {
687
            width = 1;
688
        }
689

    
690
        if (height <= 0) {
691
            height = 1;
692
        }
693

    
694
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
695
        pRGBArray = new int[width * height];
696

    
697
        try {
698
            file.setAlpha(getAlpha());
699
            
700
            setBand(RED_BAND, rBandNr);
701
            setBand(GREEN_BAND, gBandNr);
702
            setBand(BLUE_BAND, bBandNr);
703
                     
704

    
705
            file.readScene(pRGBArray);
706
            ((BufferedImage) image).setRGB(0, 0, width, height, pRGBArray, 0,
707
                                           width);
708
        } catch (Exception e) {
709
            e.printStackTrace();
710
        }
711

    
712
        return image;
713
    }
714

    
715
    /**
716
     * Muestra informaci?n del fichero abierto.
717
     *
718
     */
719
    private void showOnOpen() {
720
        // Report en la apertura (quitar)
721
        System.out.println("Fichero MrSID '" + getName() + "' abierto.");
722
        System.out.println("Version = " + file.version);
723
        System.out.println("   Size = (" + file.width + "," + file.height +
724
                           ")");
725
        System.out.println("   NumBands = (" + file.nbands + ")");
726

    
727
        //file.pintaInfo();
728
        file.pintaPaleta();
729
    }
730

    
731
    /**
732
     * Asigna al objeto Image los valores con los dato de la imagen contenidos en el
733
     * vector de enteros.
734
     * @param image        imagen con los datos actuales
735
     * @param startX        inicio de la posici?n en X dentro de la imagen
736
     * @param startY        inicio de la posici?n en X dentro de la imagen
737
     * @param w        Ancho de la imagen
738
     * @param h        Alto de la imagen
739
     * @param rgbArray        vector que contiene la banda que se va a sustituir
740
     * @param offset        desplazamiento
741
     * @param scansize        tama?o de imagen recorrida por cada p
742
     */
743
    protected void setRGBLine(BufferedImage image, int startX, int startY,
744
                              int w, int h, int[] rgbArray, int offset,
745
                              int scansize) {
746
        image.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
747
    }
748

    
749
    /**
750
     * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
751
     * con los datos de la imagen contenidos en el vector de enteros. De los valores RGB
752
     * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
753
     * banda correspondiente a flags es sustituida por los datos del vector.
754
     * @param image        imagen con los datos actuales
755
     * @param startX        inicio de la posici?n en X dentro de la imagen
756
     * @param startY        inicio de la posici?n en X dentro de la imagen
757
     * @param w        Ancho de la imagen
758
     * @param h        Alto de la imagen
759
     * @param rgbArray        vector que contiene la banda que se va a sustituir
760
     * @param offset        desplazamiento
761
     * @param scansize        tama?o de imagen recorrida por cada paso
762
     * @param flags        banda que se va a sustituir (Ctes de GeoRasterFile)
763
     */
764
    protected void setRGBLine(BufferedImage image, int startX, int startY,
765
                              int w, int h, int[] rgbArray, int offset,
766
                              int scansize, int flags) {
767
        int[] line = new int[rgbArray.length];
768
        image.getRGB(startX, startY, w, h, line, offset, scansize);
769

    
770
        if (flags == GeoRasterFile.RED_BAND) {
771
            for (int i = 0; i < line.length; i++)
772
                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
773
        } else if (flags == GeoRasterFile.GREEN_BAND) {
774
            for (int i = 0; i < line.length; i++)
775
                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
776
        } else if (flags == GeoRasterFile.BLUE_BAND) {
777
            for (int i = 0; i < line.length; i++)
778
                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
779
        }
780

    
781
        image.setRGB(startX, startY, w, h, line, offset, scansize);
782
    }
783

    
784
    /**
785
     * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
786
     * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
787
     * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
788
     * banda correspondiente a flags es sustituida por los datos del vector.
789
     * @param image        imagen con los datos actuales
790
     * @param startX        inicio de la posici?n en X dentro de la imagen
791
     * @param startY        inicio de la posici?n en X dentro de la imagen
792
     * @param w        Ancho de la imagen
793
     * @param h        Alto de la imagen
794
     * @param rgbArray        vector que contiene la banda que se va a sustituir
795
     * @param offset        desplazamiento
796
     * @param scansize        tama?o de imagen recorrida por cada paso
797
     * @param origBand        Banda origen del GeoRasterFile
798
     * @param destBandFlag        banda que se va a sustituir (Ctes de GeoRasterFile)
799
     */
800
    protected void setRGBLine(BufferedImage image, int startX, int startY,
801
                              int w, int h, int[] rgbArray, int offset,
802
                              int scansize, int origBand, int destBandFlag) {
803
        int[] line = new int[rgbArray.length];
804
        image.getRGB(startX, startY, w, h, line, offset, scansize);
805

    
806
        if ((origBand == 0) && (destBandFlag == GeoRasterFile.RED_BAND)) {
807
            for (int i = 0; i < line.length; i++)
808
                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
809
        } else if ((origBand == 1) &&
810
                       (destBandFlag == GeoRasterFile.GREEN_BAND)) {
811
            for (int i = 0; i < line.length; i++)
812
                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
813
        } else if ((origBand == 2) &&
814
                       (destBandFlag == GeoRasterFile.BLUE_BAND)) {
815
            for (int i = 0; i < line.length; i++)
816
                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
817
        } else if ((origBand == 0) &&
818
                       (destBandFlag == GeoRasterFile.GREEN_BAND)) {
819
            for (int i = 0; i < line.length; i++)
820
                line[i] = (line[i] & 0xffff00ff) |
821
                          ((rgbArray[i] & 0x00ff0000) >> 8);
822
        } else if ((origBand == 0) &&
823
                       (destBandFlag == GeoRasterFile.BLUE_BAND)) {
824
            for (int i = 0; i < line.length; i++)
825
                line[i] = (line[i] & 0xffffff00) |
826
                          ((rgbArray[i] & 0x00ff0000) >> 16);
827
        } else if ((origBand == 1) && (destBandFlag == GeoRasterFile.RED_BAND)) {
828
            for (int i = 0; i < line.length; i++)
829
                line[i] = (line[i] & 0xff00ffff) |
830
                          ((rgbArray[i] & 0x0000ff00) << 8);
831
        } else if ((origBand == 1) &&
832
                       (destBandFlag == GeoRasterFile.BLUE_BAND)) {
833
            for (int i = 0; i < line.length; i++)
834
                line[i] = (line[i] & 0xffffff00) |
835
                          ((rgbArray[i] & 0x0000ff00) >> 8);
836
        } else if ((origBand == 2) && (destBandFlag == GeoRasterFile.RED_BAND)) {
837
            for (int i = 0; i < line.length; i++)
838
                line[i] = (line[i] & 0xff00ffff) |
839
                          ((rgbArray[i] & 0x000000ff) << 16);
840
        } else if ((origBand == 2) &&
841
                       (destBandFlag == GeoRasterFile.GREEN_BAND)) {
842
            for (int i = 0; i < line.length; i++)
843
                line[i] = (line[i] & 0xffff00ff) |
844
                          ((rgbArray[i] & 0x000000ff) << 8);
845
        }
846

    
847
        image.setRGB(startX, startY, w, h, line, offset, scansize);
848
    }
849

    
850
    /* (non-Javadoc)
851
     * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans, java.awt.Image, int)
852
     */
853
    public Image updateImage(int width, int height, ICoordTrans rp, Image img,
854
                             int origBand, int destBandFlag) throws SupersamplingNotSupportedException{
855
        int line;
856
        int[] pRGBArray = null;
857
        Image mrSidImage = null;
858

    
859
        if(mustVerifySize()){
860
                // Work out the correct aspect for the setView call.
861
                double dFileAspect = (double) v.width() / (double) v.height();
862
                double dWindowAspect = (double) width / (double) height;
863
        
864
                if (dFileAspect > dWindowAspect) {
865
                    height = (int) ((double) width / dFileAspect);
866
                } else {
867
                    width = (int) ((double) height * dFileAspect);
868
                }
869
        }
870
        // Set the view
871
        file.setView(v.minX(), v.maxY(), v.maxX(), v.minY(), width, height);
872

    
873
        //Impedimos que los valores de ancho y alto de la im?gen sean menores que 1
874
        if (width <= 0) {
875
            width = 1;
876
        }
877

    
878
        if (height <= 0) {
879
            height = 1;
880
        }
881

    
882
        file.setAlpha(getAlpha());
883
      
884
        setBand(RED_BAND, rBandNr);
885
        setBand(GREEN_BAND, gBandNr);
886
        setBand(BLUE_BAND, bBandNr);
887
       
888
        pRGBArray = new int[width * height];
889

    
890
        if (img == null) { //Caso en el que se crea una imagen
891
            mrSidImage = new BufferedImage(width, height,
892
                                           BufferedImage.TYPE_INT_ARGB);
893

    
894
            try {
895
                file.readScene(pRGBArray);
896
                setRGBLine((BufferedImage) mrSidImage, 0, 0, width, height, pRGBArray, 0, width);
897
            } catch (Exception e) {
898
                e.printStackTrace();
899
            }
900

    
901
            return mrSidImage;
902
        } else { //Caso en el que se actualiza una banda del Image
903

    
904
            try {
905
                file.readScene(pRGBArray);
906
                setRGBLine((BufferedImage) img, 0, 0, width, height, pRGBArray, 0, width, origBand, destBandFlag);
907
            } catch (Exception e) {
908
                e.printStackTrace();
909
            }
910

    
911
            return img;
912
        }
913
    }
914

    
915
    /* (non-Javadoc)
916
     * @see org.cresques.io.GeoRasterFile#getData(int, int, int)
917
     */
918
    public Object getData(int x, int y, int band) {
919
        // TODO Auto-generated method stub
920
        return null;
921
    }
922

    
923
    /**
924
     * Devuelve los datos de una ventana solicitada
925
     * @param ulX        coordenada X superior izda.
926
     * @param ulY        coordenada Y superior derecha.
927
     * @param sizeX        tama?o en X de la ventana.
928
     * @param sizeY tama?o en Y de la ventana.
929
     * @param band        Banda solicitada.
930
     */
931
    public byte[] getWindow(int ulX, int ulY, int sizeX, int sizeY, int band) {
932
        try {
933
            return file.getWindow(ulX, ulY, sizeX, sizeY, band);
934
        } catch (MrSIDException e) {
935
            e.printStackTrace();
936
        }
937

    
938
        return null;
939
    }
940

    
941
    /**
942
     * Devuelve el tama?o de bloque
943
     * @return Tama?o de bloque
944
     */
945
    public int getBlockSize() {
946
        return file.blocksize;
947
    }
948
    
949
    /**
950
         * Calcula la transformaci?n que se produce sobre la vista cuando la imagen tiene un fichero .rmf
951
         * asociado. En Ecw el origen de coordenadas en Y es el valor m?ximo y decrece hasta el m?nimo.
952
         * @param originX Origen de la imagen en la coordenada X
953
         * @param originY Origen de la imagen en la coordenada Y
954
         */
955
    public void setExtentTransform(double originX, double originY, double psX, double psY) {
956
                
957
        }
958
}