Statistics
| Revision:

svn-gvsig-desktop / tags / v1_0_2_Build_907 / libraries / libCq CMS for java.old / src / org / cresques / io / ErmapperWriter.java @ 11015

History | View | Annotate | Download (28.2 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.io.IOException;
27

    
28
import org.cresques.geo.ViewPortData;
29
import org.cresques.i18n.Messages;
30
import org.cresques.io.data.WriterSupportOptions;
31
import org.cresques.px.PxRaster;
32

    
33
import es.gva.cit.jecwcompress.CompressFormat;
34
import es.gva.cit.jecwcompress.EcwException;
35
import es.gva.cit.jecwcompress.JniObject;
36
import es.gva.cit.jecwcompress.NCSEcwCompressClient;
37
import es.gva.cit.jecwcompress.ReadCallBack;
38
import es.gva.cit.jgdal.GdalRasterBand;
39

    
40

    
41
/**
42
 * Driver para la compresi?n en formato Ecw.
43
 *
44
 * Puede exportar un fichero desde un GeoRasterFile en cualquier formato soportado
45
 * por los drivers de lectura a uno en formato Ecw.
46
 *
47
 * Puede salvar a disco en formato Ecw obteniendo los datos que van siendo servidos
48
 * desde el cliente. Este cliente debe implementar un IDataWriter o tener un objeto
49
 * que lo implemente. Inicialmente le pasar? los par?metros de la imagen de salida
50
 * y cuando el driver comience a escribir le ir? solicitando m?s a trav?s del m?todo
51
 * readData de IDataWriter. El cliente ser? el que lleve el control de lo que va
52
 * sirviendo y lo que le queda por servir.
53
 * @author Nacho Brodin (brodin_ign@gva.es)
54
 */
55
public class ErmapperWriter extends GeoRasterWriter {
56
    static {
57
            String os = System.getProperties().getProperty("os.version");
58
        if (os.startsWith("2.4")){
59
                GeoRasterWriter.registerWriterExtension("ecw", ErmapperWriter.class);
60
                typeList.put("ecw", "Ecw");
61
        }
62
        GeoRasterWriter.registerWriterExtension("jp2", ErmapperWriter.class);
63
        typeList.put("jp2", "Jpeg2000");
64
    }
65

    
66
    public final int                                 windowSizeX = 386;
67
    public final int                                 windowSizeY = 220;
68
    public final int                                 panelSizeX = 358;
69
    public final int                                 panelSizeY = 125;
70
    public final String                         panelLayout = "BorderLayout";
71
    private NCSEcwCompressClient         compressclient = null;
72
    private Reader                                         readerObj;
73
    private double                                         pixelSizeX;
74
    private double                                         pixelSizeY;
75
    private double                                         geoCoordOrigenX;
76
    private double                                         geoCoordOrigenY;
77
    private EcwSupportOptions                 support = null;
78
    private boolean                                 consulta = false;
79

    
80
    /**
81
     * Constructor para la obtenci?n de par?metros del driver.
82
     */
83
    public ErmapperWriter(String fileName) {
84
            ident = fileName.toLowerCase().substring(fileName.lastIndexOf(".") + 1);            
85
            driver = (String)typeList.get(ident);
86
            
87
        support = new EcwSupportOptions(driver);
88
        support.setBlockSize(blockSizeDefault);
89
        support.setCompressionDefault(10);
90
        support.setFormatDefault(4);
91
        support.setWriteGeoref(true);
92
        consulta = true;
93
    }
94

    
95
    /**
96
     * Constructor para salvar una sola imagen completa
97
     * @param raster        PxRaster de la imagen origen
98
     * @param outfilename        Fichero de salida
99
     * @param infilename        Fichero de entrada
100
     * @param compresion        Compresi?n
101
     */
102
    public ErmapperWriter(PxRaster raster, String outFileName, String inFileName,
103
                     int compresion) throws EcwException, IOException {
104
            ident = outFileName.toLowerCase().substring(outFileName.lastIndexOf(".") + 1); 
105
            driver = (String)typeList.get(ident);
106
        support = new EcwSupportOptions(driver);
107
        
108
        this.outFileName = outFileName;
109
        this.inFileName = inFileName;
110
        currentRaster = raster;
111

    
112
        support.setCompressionDefault(compresion);
113

    
114
        sizeWindowX = raster.getFWidth();
115
        sizeWindowY = raster.getFHeight();
116

    
117
        support.setBlockSize(currentRaster.getBlockSize());
118

    
119
        nBands = currentRaster.getBandCount();
120

    
121
        //Calculamos la georeferenciaci?n
122
        double maxX = currentRaster.getExtent().maxX();
123
        geoCoordOrigenX = currentRaster.getExtent().minX();
124
        geoCoordOrigenY = currentRaster.getExtent().maxY();
125

    
126
        double minY = currentRaster.getExtent().minY();
127
        double w = currentRaster.getFWidth();
128
        double h = currentRaster.getFHeight();
129
        pixelSizeX = (maxX - geoCoordOrigenX) / w;
130
        pixelSizeY = (minY - geoCoordOrigenY) / h;
131

    
132
        if ((sizeWindowX < 0) || (sizeWindowY < 0)) {
133
            throw new IOException("Tama?o del fichero de salida erroneo.");
134
        }
135

    
136
        if (nBands == 1) {
137
            this.support.setFormatDefault(CompressFormat.COMPRESS_UINT8);
138
        } else if (nBands == 3) {
139
            this.support.setFormatDefault(CompressFormat.COMPRESS_RGB);
140
        } else {
141
            this.support.setFormatDefault(CompressFormat.COMPRESS_MULTI);
142
        }
143

    
144
        init();
145
    }
146

    
147
    /**
148
     * Constructor para la lectura de datos desde el objeto cliente a partir
149
     * de un viewport dado.
150
     * @param dataWriter        Objeto que sirve datos para el escritor
151
     * @param vp        viewport de origen
152
     * @param outFileName        Fichero de salida
153
     * @param blockSize        Tama?o de bloque
154
     * @param nBands        N?mero de bandas
155
     * @param compresion        Compresi?n
156
     * @throws EcwException
157
     * @throws IOException
158
     */
159
    public ErmapperWriter(        IDataWriter dataWriter, 
160
                                     String outFileName, 
161
                                     Integer blockSize, 
162
                                     Integer nBands,
163
                                     ViewPortData vp,
164
                                     Integer compresion,
165
                                     Integer outSizeX,
166
                                     Integer outSizeY) throws EcwException, IOException {
167
            ident = outFileName.toLowerCase().substring(outFileName.lastIndexOf(".") + 1); 
168
            driver = (String)typeList.get(ident);
169
        support = new EcwSupportOptions(driver);
170
        int comp = compresion.intValue();
171
        
172
        if (comp <= 0)
173
            comp = 1;
174

    
175
        if (nBands.intValue() <= 0) {
176
            throw new EcwException("N?mero de bandas erroneo.");
177
        }
178

    
179
        if ((vp.getWidth() <= 0) || (vp.getHeight() <= 0)) {
180
            throw new EcwException("Tama?o de la imagen de salida erroneo.");
181
        }
182

    
183
        this.outFileName = outFileName;
184
        this.dataWriter = dataWriter;
185
        this.support.setCompressionDefault(compresion.intValue());
186
        this.nBands = nBands.intValue();
187

    
188
        this.sizeWindowX = (int) vp.getWidth();
189
        this.sizeWindowY = (int) vp.getHeight();
190
        this.support.setBlockSize(blockSize.intValue());
191

    
192
        //Calculamos la georeferenciaci?n a partir del extend pasado por el cliente.
193
        double maxX = vp.getExtent().maxX();
194
        geoCoordOrigenX = vp.getExtent().minX();
195
        geoCoordOrigenY = vp.getExtent().maxY();
196

    
197
        double minY = vp.getExtent().minY();
198
        pixelSizeX = (maxX - geoCoordOrigenX) / vp.getWidth();
199
        pixelSizeY = (minY - geoCoordOrigenY) / vp.getHeight();
200

    
201
        if (pixelSizeX == 0) {
202
            pixelSizeX = 1.0;
203
        }
204

    
205
        if (pixelSizeY == 0) {
206
            pixelSizeY = 1.0;
207
        }
208

    
209
        init();
210
    }
211

    
212
    /**
213
     * Inicializaci?n de los par?metros del compresor que ser?n obtenidos
214
     * de PxRaster.
215
     * @throws EcwException
216
     */
217
    private void init() throws EcwException {
218
        if (this.support.getCompression() == 0) {
219
            this.support.setCompressionDefault(1);
220
        }
221

    
222
        if (compressclient == null) {
223
            compressclient = new NCSEcwCompressClient();
224
        }
225

    
226
        compressclient.setOutputFilename(outFileName);
227
        compressclient.setInputFilename("");
228
        compressclient.setTargetCompress(this.support.getCompression());
229
        //compressclient.setActualCompression(this.support.getCompression());
230
        compressclient.setInOutSizeX(sizeWindowX);
231
        compressclient.setInOutSizeY(sizeWindowY);
232
        compressclient.setInputBands(nBands);
233
        compressclient.setCompressFormat(this.support.getFormat());
234

    
235
        //System.out.println("Origen=>"+minX + "  "+maxY );
236
        //System.out.println("Pixel Size=>"+psX+"  "+psY);
237
        //compressclient.setDatum("UTM Zona 31N");
238
        //client.setProjection("WGS84");
239
        if (this.support.getGeoref()) {
240
            compressclient.setCellIncrementX(pixelSizeX);
241
            compressclient.setCellIncrementY(pixelSizeY);
242
            compressclient.setOriginX(geoCoordOrigenX);
243
            compressclient.setOriginY(geoCoordOrigenY);
244
        }
245

    
246
        compressclient.setCellSizeUnits(1);
247
        
248
        //System.out.println(outfilename+" "+infilename+" "+compresion+" "+sizeWindowX+" "+sizeWindowY+" "+currentRaster.getBandCount());
249
        //System.out.println(psX+" "+psY+" "+minX+" "+maxX);
250
        if (currentRaster != null) {
251
            readerObj = new Reader(currentRaster.getGeoFile(), compressclient,
252
                                   ulX, ulY, sizeWindowX, sizeWindowY,
253
                                   this.support.getBlockSize());
254
        } else if (dataWriter != null) {
255
            readerObj = new Reader(dataWriter, compressclient, sizeWindowX,
256
                                   sizeWindowY, this.support.getBlockSize(),
257
                                   this.nBands);
258
        }
259
    }
260

    
261
    /**
262
     * A partir de un elemento que contiene una propiedad y un valor
263
     * lo parsea y asigna el valor a su variable.
264
     * @param propValue        elemento con la forma propiedad=valor
265
     */
266
    private void readProperty(String propValue) {
267
        String prop = propValue.substring(0, propValue.indexOf("="));
268

    
269
        if (propValue.startsWith(prop)) {
270
            String value = propValue.substring(propValue.indexOf("=") + 1,
271
                                               propValue.length());
272

    
273
            if ((value != null) && !value.equals("")) {
274
                if (prop.equals("BLOCKSIZE")) {
275
                    this.support.setBlockSize(Integer.parseInt(value));
276
                }
277

    
278
                if (prop.equals("FORMAT")) {
279
                    int select = 0;
280

    
281
                    if (value.equals("UINT8")) {
282
                        select = 1;
283
                    }
284

    
285
                    if (value.equals("YUV")) {
286
                        select = 2;
287
                    }
288

    
289
                    if (value.equals("MULTI")) {
290
                        select = 3;
291
                    }
292

    
293
                    if (value.equals("RGB")) {
294
                        select = 4;
295
                    }
296

    
297
                    this.support.setFormatDefault(select);
298
                }
299

    
300
                if (prop.equals("GEOREF")) {
301
                    boolean georef = true;
302

    
303
                    if (value.equals("yes")) {
304
                        georef = true;
305
                    } else {
306
                        georef = false;
307
                    }
308

    
309
                    this.support.setWriteGeoref(georef);
310
                }
311

    
312
                if (prop.equals("COMPRESSION")) {
313
                    this.support.setCompressionDefault(Integer.parseInt(value));
314
                }
315
            }
316
        }
317
    }
318

    
319
    /**
320
     * Asigna propiedades al driver a partir de un vector de
321
     * strings donde cada elemento tiene la estructura de
322
     * propiedad=valor.
323
     * @param props        Propiedades
324
     */
325
    public void setProps(String[] props) {
326
        for (int iProps = 0; iProps < props.length; iProps++)
327
            readProperty(props[iProps]);
328

    
329
        try {
330
            if (!consulta) {
331
                init();
332
            }
333
        } catch (EcwException e) {
334
            e.printStackTrace();
335
        }
336
    }
337

    
338
    /**
339
     * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
340
     * @throws IOException
341
     */
342
    public void fileWrite() throws IOException {
343
        if (currentRaster == null) {
344
            throw new IOException("No se ha asignado un fichero de entrada.");
345
        }
346

    
347
        try {
348
            compressclient.NCSEcwCompressOpen(false);
349
            compressclient.NCSEcwCompress(readerObj);
350
        } catch (EcwException e) {
351
            e.printStackTrace();
352
        }
353
    }
354

    
355
    /**
356
     * Realiza la funci?n de compresi?n a partir de los datos pasados por el cliente.
357
     * @throws IOException
358
     */
359
    public void dataWrite() throws IOException {
360
        if (dataWriter == null) {
361
            throw new IOException("No se ha obtenido un objeto para la lectura valido.");
362
        }
363

    
364
        try {
365
            compressclient.NCSEcwCompressOpen(false);
366
            compressclient.NCSEcwCompress(readerObj);
367
        } catch (EcwException e) {
368
            e.printStackTrace();
369
        }
370
    }
371

    
372
    /**
373
     * Cierra el compresor ecw.
374
     */
375
    public void writeClose() {
376
        try {
377
            compressclient.NCSEcwCompressClose();
378
        } catch (EcwException e) {
379
            e.printStackTrace();
380
        }
381
    }
382
    
383
    /**
384
     * Cancela el compresor ecw.
385
     */
386
    public void writeCancel() {
387
        try {
388
                if(readerObj != null)
389
                        readerObj.setWrite(false);
390
            compressclient.NCSEcwCompressCancel();
391
        } catch (EcwException e) {
392
            e.printStackTrace();
393
        }
394
    }
395

    
396
    /**
397
     * Devuelve la configuraci?n de la ventana de dialogo
398
     * para las propiedades del driver de escritura de Ecw.
399
     * @return XML de configuraci?n del dialogo.
400
     */
401
    public String getXMLPropertiesDialog() {
402
        StringBuffer options = null;
403
        options = new StringBuffer();
404
        options.append("<window sizex=\"" + this.windowSizeX + "\" sizey=\"" +
405
                       this.windowSizeY + "\">");
406
        options.append("<panel sizex=\"" + this.panelSizeX + "\" sizey=\"" +
407
                       this.panelSizeY + "\" layout=\"" + this.panelLayout +
408
                       "\" border=\"yes\">");
409

    
410
        options.append("<panel layout=\"FlowLayout\" position=\"North\" align=\"left\">");
411
        options.append("<label>"+Messages.getText("Block_Size_")+"</label>");
412
        options.append("<combo ident=\"BLOCKSIZE\" selected=\"" +
413
                       this.support.getBlockSize() + "\">");
414

    
415
        for (int i = 0; i < this.support.getBlockSizeList().length; i++)
416
            options.append("<elem>" + this.support.getBlockSizeList()[i] +
417
                           "</elem>");
418

    
419
        options.append("</combo>");
420
        /*options.append("<label>Formato:</label>");
421

422
        String sel = null;
423

424
        if (this.support.getGeoref()) {
425
            sel = new String("yes");
426
        } else {
427
            sel = new String("no");
428
        }
429

430
        options.append("<check ident=\"GEOREF\" selected=\"" + sel +
431
                       "\" text=\"Georef Si/No\">");
432
        options.append("</check>");*/
433
        options.append("</panel>");
434

    
435
        options.append("<panel layout=\"FlowLayout\" position=\"South\">");
436
        options.append("<slider ident=\"COMPRESSION\" name=\"Nivel de Compresi?n\" sizex=\"350\" sizey=\"20\">");
437
        options.append("<min>" + this.support.getCompressionList()[0] +
438
                       "</min>");
439
        options.append("<max>" + this.support.getCompressionList()[1] +
440
                       "</max>");
441
        options.append("<value>" + this.support.compresionDefault + "</value>");
442
        options.append("<minorspacing>" + this.support.getCompressionList()[3] +
443
                       "</minorspacing>");
444
        options.append("<majorspacing>" + this.support.getCompressionList()[4] +
445
                       "</majorspacing>");
446
        options.append("</slider>");
447
        options.append("</panel>");
448

    
449
        options.append("</panel>");
450
        options.append("</window>");
451

    
452
        return options.toString();
453
    }
454

    
455
    /**
456
     * @author Nacho Brodin <brodin_ign@gva.es>
457
     *
458
     * Opciones de escritura para el Ecw. Estas opciones son utilizadas para el
459
     * dialogo de propiedades de Salvar a Raster en Ecw.
460
     */
461
    class EcwSupportOptions extends WriterSupportOptions {
462
        private String[] compresionListValues = { "0", "20", "10", "1", "5" }; //min, max, valor defecto, intervalo peque?o, intervalo grande;
463
        private String[] formatList = { "NONE", "UINT8", "YUV", "MULTI", "RGB" };
464
        private int formatDefault = 4;
465
        private int compresionDefault = 10;
466

    
467
        EcwSupportOptions(String drv) {
468
            super(drv);
469
        }
470

    
471
        /**
472
         * Asigna la lista de valores de compresi?n
473
         * @param compresion        lista de valores
474
         */
475
        public void setCompressionList(String[] compresion) {
476
            this.compresionListValues = compresion;
477
        }
478

    
479
        /**
480
         * Valor de formato seleccionado en el driver.
481
         * 0-NONE, 1-UINT8, 2-YUV, 3-MULTI, 4-RGB
482
         * @param i        valor de formato
483
         */
484
        public void setFormatDefault(int i) {
485
            this.formatDefault = i;
486
        }
487

    
488
        /**
489
         * Asigna el nivel de compresi?npor defecto
490
         * @param compress        Nivel de compresi?n
491
         */
492
        public void setCompressionDefault(int compress) {
493
            this.compresionDefault = compress;
494
        }
495

    
496
        /**
497
         * Obtiene el tipo de imagen en un formato comprensible por el driver.
498
         * @return        Tipo de imagen
499
         */
500
        public String getStringFormat() {
501
            return "COMPRESS_" + formatList[formatDefault];
502
        }
503

    
504
        /**
505
         * Obtiene la lista de los tipos de formato disponible
506
         * @return Lista de tipos de formato
507
         */
508
        public String[] getFormatList() {
509
            return formatList;
510
        }
511

    
512
        /**
513
         * Obtiene el tipo de formato seleccionado en el driver
514
         * @return Tipo de formato seleccionado
515
         */
516
        public int getFormat() {
517
            return formatDefault;
518
        }
519

    
520
        /**
521
         * Obtiene la compresion seleccionada
522
         * @return Compresi?n seleccionada
523
         */
524
        public int getCompression() {
525
            return compresionDefault;
526
        }
527

    
528
        /**
529
         * Obtiene la lista de los valores para la generaci?n de la barra de
530
         * compresi?n. Son cinco valores m?nimo, m?ximo, seleccionado,
531
         * intervalo peque?o, intervalo grande.
532
         * @return lista de valores de compresi?n
533
         */
534
        public String[] getCompressionList() {
535
            return compresionListValues;
536
        }
537
    }
538
}
539

    
540

    
541
/**
542
 * Clase que se encarga de la lectura de datos que ser?n escritos. Hereda de JniObject
543
 * para asegurar  para asegurar que el interfaz de la libreria tiene acceso a variables
544
 * necesarias para la petici?n de datos cuando vacia el buffer. Implementa ReadCallBack
545
 * para obligar escribir el m?todo loadBuffer encargado de servir los datos cuando el
546
 * buffer se vacia.
547
 *
548
 */
549
class Reader extends JniObject implements ReadCallBack {
550
    private NCSEcwCompressClient        compressclient = null;
551
    private int                                         width;
552
    private int                                         height;
553
    private int                                         ulX;
554
    private int                                         ulY;
555
    private GeoRasterFile                         grf = null;
556
    private IDataWriter                         dataWriter = null;
557
    private GdalRasterBand                         rband = null;
558
    private int                                         blockSizeRead = 1; //Alto del bloque leido de la imagen origen 
559
    private int                                         countLine = 1; //Contador de l?neas procesadas en cada lectura de bloque
560
    byte[][]                                                 buf = null;
561
    byte[]                                                         bufband1 = null;
562
    byte[]                                                         bufband2 = null;
563
    byte[]                                                         bufband3 = null;
564
    byte[]                                                         bufband4 = null;
565
    byte[]                                                         bufband5 = null;
566
    byte[]                                                         bufband6 = null;
567
    int[]                                                         dataBuffer = null;
568
    private int                                         lineasBloqueFinal = 0; //N?mero de l?neas leidas del bloque final
569
    private int                                         nBlocks = 0; //N?mero de bloques completos
570
    private int                                         countBlock = 1; //Contador de bloques completos procesados
571
    private int                                         nBands = 0;
572
    private        boolean                                        write = true; //Cuando est? a true se puede escribir en la imagen de salida. Si est? a false el proceso es interrumpido
573

    
574
    /**
575
     * Constructor para la escritura de un fichero desde un GeoRasterFile
576
     * @param grf        GeorasterFile del fichero de origen
577
     * @param compressclient        Objeto que representa al compresor ecw
578
     * @param ulx        Coordenada X de la esquina superior izquierda
579
     * @param uly        Coordenada Y de la esquina superior izquierda
580
     * @param width        Ancho de la imagen
581
     * @param height        Alto de la imagen
582
     * @param blockSizeRead        Altura del bloque en la lectura
583
     */
584
    public Reader(GeoRasterFile grf, NCSEcwCompressClient compressclient,
585
                  int ulx, int uly, int width, int height, int blockSizeRead) {
586
        this.compressclient = compressclient;
587
        this.width = width;
588
        this.height = height;
589
        this.ulX = ulx;
590
        this.ulY = uly;
591
        this.grf = grf;
592
        this.nBands = grf.getBandCount();
593

    
594
        if (blockSizeRead != 0) {
595
            this.blockSizeRead = blockSizeRead;
596
        }
597

    
598
        nBlocks = (int) (height / this.blockSizeRead);
599
        lineasBloqueFinal = height - (nBlocks * this.blockSizeRead);
600

    
601
    }
602

    
603
    /**
604
     * Constructor para que los datos sean servidos desde el cliente a trav?s de un
605
     * IDataWriter.
606
     * @param dataWriter        Objeto servidor de datos del driver
607
     * @param compressclient        Objeto que representa al compresor ecw
608
     * @param width        Ancho de la imagen
609
     * @param height        Alto de la imagen
610
     * @param blockSizeRead        Altura del bloque en la lectura
611
     * @param nBands        N?mero de bandas
612
     */
613
    public Reader(IDataWriter dataWriter, NCSEcwCompressClient compressclient,
614
                  int width, int height, int blockSizeRead, int nBands) {
615
        this.compressclient = compressclient;
616
        this.width = width;
617
        this.height = height;
618
        this.dataWriter = dataWriter;
619
        this.nBands = nBands;
620

    
621
        if (blockSizeRead != 0) {
622
            this.blockSizeRead = blockSizeRead;
623
        }
624

    
625
        nBlocks = (int) (height / this.blockSizeRead);
626
        lineasBloqueFinal = height - (nBlocks * this.blockSizeRead);
627

    
628
    }
629

    
630
    /**
631
     * Lectura de bandas desde un GeoRasterFile
632
     * @param ulX        Coordenada X de la esquina superior izquierda
633
     * @param ulY        Coordenada Y de la esquina superior izquierda
634
     * @param width        Ancho de la imagen
635
     * @param lineasLeidas        N?mero de l?neas a leer del origen
636
     */
637
    private void readBandsGRFile(int ulX, int ulY, int width, int lineasLeidas) {
638
        if (nBands >= 1) {
639
            bufband1 = grf.getWindow(ulX, ulY, width, lineasLeidas, 1);
640
        }
641

    
642
        if (nBands >= 2) {
643
            bufband2 = grf.getWindow(ulX, ulY, width, lineasLeidas, 2);
644
        }
645

    
646
        if (nBands >= 3) {
647
            bufband3 = grf.getWindow(ulX, ulY, width, lineasLeidas, 3);
648
        }
649

    
650
        if (nBands >= 4) {
651
            bufband4 = grf.getWindow(ulX, ulY, width, lineasLeidas, 4);
652
        }
653

    
654
        if (nBands >= 5) {
655
            bufband5 = grf.getWindow(ulX, ulY, width, lineasLeidas, 5);
656
        }
657

    
658
        if (nBands >= 6) {
659
            bufband6 = grf.getWindow(ulX, ulY, width, lineasLeidas, 6);
660
        }
661
    }
662

    
663
    /**
664
     * Lectura de bandas llamando al objeto cliente para que nos cargue el buffer
665
     * @param width        Ancho de la imagen
666
     * @param height        Alto de la imagen
667
     */
668
    private void readBands(int width, int height) {
669
        dataBuffer = dataWriter.readData(width, height, 0);
670
    }
671

    
672
    /**
673
     * M?todo obligado por el interfaz y que es llamado desde C cuando el
674
     * compresor necesita que le sirvan m?s datos.
675
     */
676
    public void loadBuffer() {
677
        int lineasLeidas = 0;
678

    
679
        //si se leen bloques completos lineasLeidas es == al tama?o de bloque sino
680
        //es que es el ?ltimo con lo que ser? del tama?o del bloque final
681
        if (countBlock <= nBlocks) {
682
            lineasLeidas = blockSizeRead;
683
        } else {
684
            lineasLeidas = lineasBloqueFinal;
685
        }
686

    
687
        //Leemos un bloque nuevo cuando se han procesado todas las l?neas del anterior
688
        if ((nNextLine % blockSizeRead) == 0) {
689
            if (grf != null) {
690
                readBandsGRFile(ulX, ulY + nNextLine, width, lineasLeidas);
691
            } else if (dataWriter != null) {
692
                readBands(width, lineasLeidas);
693
            }
694

    
695
            countLine = 0;
696
            countBlock++;
697
        }
698

    
699
        for (int iBand = 0; iBand < this.nBands; iBand++) {
700
            for (int pos = 0; pos < width; pos++) {
701
                if (grf != null && write) {
702
                    if (iBand == 0) {
703
                        compressclient.buffer[pos + (width * iBand)] = bufband1[pos +
704
                                                                       (width * countLine)];
705
                    }
706

    
707
                    if (iBand == 1) {
708
                        compressclient.buffer[pos + (width * iBand)] = bufband2[pos +
709
                                                                       (width * countLine)];
710
                    }
711

    
712
                    if (iBand == 2) {
713
                        compressclient.buffer[pos + (width * iBand)] = bufband3[pos +
714
                                                                       (width * countLine)];
715
                    }
716

    
717
                    if (iBand == 3) {
718
                        compressclient.buffer[pos + (width * iBand)] = bufband4[pos +
719
                                                                       (width * countLine)];
720
                    }
721

    
722
                    if (iBand == 4) {
723
                        compressclient.buffer[pos + (width * iBand)] = bufband5[pos +
724
                                                                       (width * countLine)];
725
                    }
726

    
727
                    if (iBand == 5) {
728
                        compressclient.buffer[pos + (width * iBand)] = bufband6[pos +
729
                                                                       (width * countLine)];
730
                    }
731
                } else {
732
                    if (iBand == 0) {
733
                        compressclient.buffer[pos + (width * iBand)] = (byte) ((dataBuffer[pos +
734
                                                                       (width * countLine)] &
735
                                                                       0xff0000) >> 16);
736
                    }
737

    
738
                    if (iBand == 1) {
739
                        compressclient.buffer[pos + (width * iBand)] = (byte) ((dataBuffer[pos +
740
                                                                       (width * countLine)] &
741
                                                                       0xff00) >> 8);
742
                    }
743

    
744
                    if (iBand == 2) {
745
                        compressclient.buffer[pos + (width * iBand)] = (byte) (dataBuffer[pos +
746
                                                                       (width * countLine)] &
747
                                                                       0xff);
748
                    }
749
                }
750

    
751
                if ((pos == (width - 1)) && (iBand == (this.nBands - 1))) {
752
                    countLine++;
753
                }
754
            }
755
        }
756
    }
757

    
758
    /**
759
     * M?todo obligado por el interfaz y que es llamado desde C cuando el
760
     * compresor actualiza el porcentaje de compresi?n
761
     */
762
    public void updatePercent() {
763
        System.out.println(compressclient.getPercent() + "%");
764
    }
765
    
766
    /**
767
     * Obtiene el valor a la variable write que estar? a true cuando se est? escribiendo
768
     *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
769
     * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
770
     * de salida. 
771
     * @return True si puede escribirse y false si no puede
772
     */
773
    public boolean isWrite() {
774
                return write;
775
        }
776

    
777
    /**
778
     * Asigna el valor a la variable write que estar? a true cuando se est? escribiendo
779
     *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
780
     * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
781
     * de salida. 
782
     * @param write Variable booleana. True si puede escribirse y false si no puede
783
     */
784
        public void setWrite(boolean write) {
785
                this.write = write;
786
        }
787
        
788
}