Statistics
| Revision:

root / trunk / libraries / libRaster / src / org / gvsig / raster / dataset / io / GdalWriter.java @ 10996

History | View | Annotate | Download (35.1 KB)

1 10960 nacho
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package org.gvsig.raster.dataset.io;
20
21
import java.io.BufferedOutputStream;
22
import java.io.DataOutputStream;
23
import java.io.File;
24
import java.io.FileOutputStream;
25
import java.io.IOException;
26
27
import org.cresques.cts.IProjection;
28
import org.gvsig.raster.dataaccess.buffer.RasterBuffer;
29
import org.gvsig.raster.dataset.GeoRasterWriter;
30
import org.gvsig.raster.dataset.IDataWriter;
31
import org.gvsig.raster.dataset.NotSupportedExtensionException;
32
import org.gvsig.raster.dataset.WriterSupportOptions;
33
import org.gvsig.raster.shared.Extent;
34
import org.gvsig.raster.util.RasterUtilities;
35
36
import es.gva.cit.jgdal.Gdal;
37
import es.gva.cit.jgdal.GdalBuffer;
38
import es.gva.cit.jgdal.GdalDriver;
39
import es.gva.cit.jgdal.GdalException;
40
import es.gva.cit.jgdal.GdalRasterBand;
41
import es.gva.cit.jgdal.GeoTransform;
42
43
44
/**
45
 * Driver para la escritura a trav?s de Gdal.
46
 * Puede exportar un fichero de un formato a otro desde un GeoRasterFile
47
 * en cualquier formato soportado por la lectura a un formato que este incluido
48
 * en la lista supportedDrv.
49
 *
50
 * Puede salvar a disco en un formato que este incluido en la lista supportedDrv
51
 * obteniendo los datos que van siendo servidos desde el cliente. Este cliente
52
 * debe implementar un IDataWriter o tener un objeto que lo implemente. Inicialmente
53
 * le pasar? los par?metros de la imagen de salida y cuando el driver comience a
54
 * escribir le ir? solicitando m?s a trav?s del m?todo readData de IDataWriter.
55
 * El cliente ser? el que lleve el control de lo que va sirviendo y lo que le queda
56
 * por servir.
57
 * @author Nacho Brodin (nachobrodin@gmail.com)
58
 */
59
public class GdalWriter extends GeoRasterWriter {
60
61
        //Datos de registro de drivers
62
    static {
63
        GeoRasterWriter.registerWriterExtension("tif", GdalWriter.class);
64
        //GeoRasterWriter.registerWriterExtension("tiff", GdalWriter.class);
65
        typeList.put("tif", "GTiff");
66
        //typeList.put("tiff", "GTiff");
67
    }
68
69
    public final int                                 windowSizeX = 386;
70
    public final int                                 windowSizeY = 195;
71
    public final int                                 panelSizeX = 358;
72
    public final int                                 panelSizeY = 105;
73
    public final String                         panelLayout = "BorderLayout";
74
    private GdalDriver                                 drv;
75
    private Gdal                                         dset_destino = null;
76
    private GdalRasterBand                         rband = null;
77
    private GeoTransform                         geot = null; //Datos de georeferenciaci?n
78
    //private OGRSpatialReference         oSRS; //Datos de proyecci?n
79
    private GdalBuffer                                 buf = null; //Buffer de origen de gdal
80
    private GdalBuffer[]                        bufBands = null;
81
    private int                                         nBlocks = 0; //N?mero de bloques en Y en el que se divide la imagen para escribir
82
    private int                                         anchoResto = 0; //Tama?o del ?ltimo bloque de la imagen.
83
    private String[]                                 params = null; //Par?metros de creaci?n del dataset.
84
    private GdalSupportOptions                 support = null;
85
    private boolean                                 consulta = false;
86
    private        boolean                                        write = true; //Cuando est? a true se puede escribir en la imagen de salida. Si est? a false el proceso es interrumpido
87
    private int                                         dataType = RasterBuffer.TYPE_UNDEFINED;
88
89
    /**
90
     * Constructor para la obtenci?n de par?metros del driver
91
     * @param drvType        Tipo de driver
92
     */
93
    public GdalWriter(String fileName) {
94
            ident = fileName.toLowerCase().substring(fileName.lastIndexOf(".") + 1);
95
            driver = (String)typeList.get(ident);
96
        support = new GdalSupportOptions(driver);
97
        support.setBlockSize(blockSizeDefault);
98
        support.setPhotometric("RGB");
99
        support.setInterleave("BAND");
100
        support.setCompress("NONE");
101
        support.setWriteGeoref(true);
102
        support.setTfw(false);
103
        consulta = true;
104
    }
105
106
    /**
107
     * Constructor para salvar una sola imagen completa
108
     * @param raster        PxRaster de la imagen de  origen
109
     * @param outfilename        Nombre del fichero de salida
110
     * @param infilename        Nombre del fichero de entrada
111
     * @param drvType        Tipo de driver
112
     */
113
    /*public GdalWriter(PxRaster raster, String outFileName, String inFileName) throws GdalException, IOException {
114
            ident = outFileName.toLowerCase().substring(outFileName.lastIndexOf(".") + 1);
115
            driver = (String)typeList.get(ident);
116
        support = new GdalSupportOptions(driver);
117

118
        this.outFileName = outFileName;
119
        this.inFileName = inFileName;
120
        currentRaster = raster;
121

122
        sizeWindowX = raster.getFWidth();
123
        sizeWindowY = raster.getFHeight();
124

125
        //Obtenemos la georeferenciaci?n
126
        if (support.getGeoref()) {
127
            double maxX = currentRaster.getExtent().maxX();
128
            double minX = currentRaster.getExtent().minX();
129
            double maxY = currentRaster.getExtent().maxY();
130
            double minY = currentRaster.getExtent().minY();
131

132
            geot = new GeoTransform();
133
            geot.adfgeotransform[0] = minX;
134
            geot.adfgeotransform[3] = maxY;
135
            geot.adfgeotransform[1] = (maxX - minX) / currentRaster.getFWidth();
136
            geot.adfgeotransform[5] = (minY - maxY) / currentRaster.getFHeight();
137
        }
138

139
        nBands = currentRaster.getBandCount();
140

141
        this.support.setBlockSize(64currentRaster.getBlockSize());
142

143
        if ((sizeWindowX < 0) || (sizeWindowY < 0)) {
144
            throw new IOException("Tama?o del fichero de salida erroneo.");
145
        }
146

147
        if (nBands == 3) {
148
            this.support.setPhotometric("PHOTOMETRIC=RGB");
149
        } else if (nBands == 1) {
150
            this.support.setPhotometric("PHOTOMETRIC=MINISBLACK");
151
        } else {
152
            this.support.setPhotometric("");
153
        }
154

155
        params = new String[2];
156
        params[0] = new String("TILED=YES");
157
        params[1] = new String(this.support.getPhotometric());
158

159
        init();*/
160
161
        /*oSRS = new OGRSpatialReference();
162
        try{
163
                oSRS.setUTM(currentRaster.geoFile.getUTM(), currentRaster.geoFile.getZone());
164
                  oSRS.setWellKnownGeogCS(currentRaster.geoFile.getGeogCS());
165
                  //System.out.println(currentRaster.geoFile.getGeogCS()+"Nueva Proyecci?n ==> "+oSRS.exportToWkt());
166
                  dset_destino.setProjection(oSRS.exportToWkt());
167
        }catch(Exception e){
168
                e.printStackTrace();
169
        }*/
170
    //}
171
172
    /**
173
     * Constructor para salvar datos servidos por el cliente
174
     * @param dataWriter               Objeto servidor de datos para el driver de escritura
175
     * @param outFilename              Fichero de salida
176
     * @param blockSize                Tama?o de bloque
177
     * @param Extent                   extent
178
     * @param compresion                   Compresi?n si la tiene
179
     * @param outSizeX                          Tama?o de salida en X
180
     * @param outSizeY                        Tama?o de salida en Y
181
     * @param dataType                        Tipo de dato
182
     * @throws GdalException
183
     * @throws IOException
184
     */
185
    public GdalWriter(        IDataWriter dataWriter,
186
                                             String outFileName,
187
                                             Integer blockSize,
188
                                             Integer nBands,
189
                                             Extent ex,
190
                                             Integer compresion,
191
                                             Integer outSizeX,
192
                                             Integer outSizeY,
193
                                             Integer dataType)throws GdalException, IOException {
194
195
            ident = outFileName.toLowerCase().substring(outFileName.lastIndexOf(".") + 1);
196
            driver = (String)typeList.get(ident);
197
        support = new GdalSupportOptions(driver);
198
        this.dataType = dataType.intValue();
199
200
        this.dataWriter = dataWriter;
201
        this.outFileName = outFileName;
202
203
        this.sizeWindowX = outSizeX.intValue();
204
        this.sizeWindowY = outSizeY.intValue();
205
206
        if ((sizeWindowX < 0) || (sizeWindowY < 0)) {
207
            throw new IOException("Tama?o del fichero de salida erroneo.");
208
        }
209
210
        this.nBands = nBands.intValue();
211
212
        //Calculamos la georeferenciaci?n a partir del extend pasado por el cliente.
213
        if (support.getGeoref()) {
214
            double maxX = ex.maxX();
215
            double minX = ex.minX();
216
            double maxY = ex.maxY();
217
            double minY = ex.minY();
218
219
            this.support.setBlockSize(blockSize.intValue());
220
221
            geot = new GeoTransform();
222
            geot.adfgeotransform[0] = minX;
223
            geot.adfgeotransform[3] = maxY; //-((pixelSizeY * outSizeY)-minY);
224
            geot.adfgeotransform[1] = (double) ((maxX - minX) / outSizeX.intValue()); //pixelSizeX;
225
            geot.adfgeotransform[5] = (double) ((minY - maxY) / outSizeY.intValue()); //pixelSizeY;
226
        }
227
228
        setParams();
229
230
        init();
231
    }
232
233
    /**
234
     *Asigna par?metros de creaci?n del dataset de Gdal
235
     */
236
    private void setParams() {
237
        params = new String[5];
238
239
        params[0] = new String("TILED=YES");
240
        params[1] = new String("PHOTOMETRIC=" + this.support.getPhotometric());
241
        params[2] = new String("INTERLEAVE=" + this.support.getInterleave());
242
        params[3] = new String("COMPRESS=" + this.support.getCompress());
243
244
        String tfw = null;
245
246
        if (this.support.getTfw()) {
247
            tfw = new String("YES");
248
        } else {
249
            tfw = new String("NO");
250
        }
251
252
        params[4] = new String("TFW=" + tfw);
253
    }
254
255
    /**
256
     * Asigna el tipo de driver con el que se salvar? la imagen
257
     * @param drvType        Tipo de driver
258
     */
259
    public void setDriverType(String drvType) {
260
        this.driver = drvType;
261
    }
262
263
    /**
264
     * Creaci?n del dataset de destino.
265
     * @throws EcwException
266
     */
267
    private void init() throws GdalException {
268
        //Controlamos que el tipo de driver sea correcto
269
        if (driver == null) {
270
            throw new GdalException("Tipo de driver sin especificar.");
271
        }
272
273
        boolean okdrvtype = false;
274
275
        String[] types = GeoRasterWriter.getDriversType();
276
        for (int i = 0; i < GeoRasterWriter.getNTypes(); i++)
277
            if (driver.equals(types[i])) {
278
                okdrvtype = true;
279
            }
280
281
        if (okdrvtype == false) {
282
            throw new GdalException("El tipo de driver "+driver+" no est? soportado por GdalWriter.");
283
        }
284
285
        //Obtenemos el driver y creamos el dataset del destino
286
        drv = Gdal.getDriverByName(driver);
287
288
        if (dset_destino != null) {
289
            dset_destino.close();
290
            dset_destino = null;
291
        }
292
293
        dset_destino = drv.create(outFileName, sizeWindowX, sizeWindowY,
294
                                  nBands, RasterUtilities.getGdalTypeFromRasterBufType(dataType), params);
295
296
        if (this.support.getGeoref()) {
297
            dset_destino.setGeoTransform(geot);
298
        }
299
300
        nBlocks = (int) (sizeWindowY / this.support.getBlockSize());
301
        anchoResto = sizeWindowY - (nBlocks * this.support.getBlockSize());
302
    }
303
304
    public void anotherFile(String fileName)throws GdalException{
305
            dset_destino = drv.create(fileName, sizeWindowX, sizeWindowY,
306
                nBands, RasterUtilities.getGdalTypeFromRasterBufType(dataType), params);
307
    }
308
309
    /**
310
     * A partir de un elemento que contiene una propiedad y un valor
311
     * lo parsea y asigna el valor a su variable.
312
     * @param propValue        elemento con la forma propiedad=valor
313
     */
314
    private void readProperty(String propValue) {
315
        String prop = propValue.substring(0, propValue.indexOf("="));
316
317
        if (propValue.startsWith(prop)) {
318
            String value = propValue.substring(propValue.indexOf("=") + 1,
319
                                               propValue.length());
320
321
            if ((value != null) && !value.equals("")) {
322
                if (prop.equals("BLOCKSIZE")) {
323
                    this.support.setBlockSize(Integer.parseInt(value));
324
                }
325
326
                if (prop.equals("GEOREF")) {
327
                    boolean georef = true;
328
329
                    if (value.equals("yes")) {
330
                        georef = true;
331
                    } else {
332
                        georef = false;
333
                    }
334
335
                    this.support.setWriteGeoref(georef);
336
                }
337
338
                if (prop.equals("INTERLEAVE")) {
339
                    this.support.setInterleave(value);
340
                }
341
342
                if (prop.equals("PHOTOMETRIC")) {
343
                    this.support.setPhotometric(value);
344
                }
345
346
                if (prop.equals("COMPRESS")) {
347
                    this.support.setCompress(value);
348
                }
349
350
                if (prop.equals("TFW")) {
351
                    boolean tfw = true;
352
353
                    if (value.equals("yes")) {
354
                        tfw = true;
355
                    } else {
356
                        tfw = false;
357
                    }
358
359
                    this.support.setTfw(tfw);
360
                }
361
            }
362
        }
363
    }
364
365
    /**
366
     * Asigna propiedades al driver a partir de un vector de
367
     * strings donde cada elemento tiene la estructura de
368
     * propiedad=valor.
369
     * @param props        Propiedades
370
     */
371
    public void setProps(String[] props) {
372
        for (int iProps = 0; iProps < props.length; iProps++)
373
            readProperty(props[iProps]);
374
375
        setParams();
376
377
        try {
378
            if (!consulta) {
379
                init();
380
            }
381
        } catch (GdalException e) {
382
            e.printStackTrace();
383
        }
384
    }
385
386
    /**
387
     * Escritura de datos tipo Byte.
388
     * @param sizeY Alto del bloque que se escribe.
389
     * @param posicionY Posici?ny a partir desde donde se comienza.
390
     */
391
    public void writeByteBand(int sizeY, int posicionY){
392
            byte[][] buftmp = dataWriter.readByteData(sizeWindowX, sizeY);
393
            for(int iBand = 0; iBand < nBands; iBand ++)
394
                bufBands[iBand].buffByte = new byte[buftmp[iBand].length];
395
396
            //Escribimos el bloque destino
397
            for (int iBand = 0; iBand < buftmp.length; iBand++)
398
                    for (int i = 0; i < buftmp[iBand].length; i++)
399
                            bufBands[iBand].buffByte[i] = buftmp[iBand][i];
400
401
        for (int iBand = 0; iBand < buftmp.length; iBand++){
402
                try {
403
                                rband = dset_destino.getRasterBand(iBand + 1);
404
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Byte);
405
                } catch (GdalException e) {
406
                                //No se est? escribiendo ...
407
                        }
408
        }
409
    }
410
411
    /**
412
     * Escritura de datos tipo Short.
413
     * @param sizeY Alto del bloque que se escribe.
414
     * @param posicionY Posici?ny a partir desde donde se comienza.
415
     */
416
    public void writeShortBand(int sizeY, int posicionY){
417
            short[][] buftmp = dataWriter.readShortData(sizeWindowX, sizeY);
418
            for(int iBand = 0; iBand < nBands; iBand ++)
419
                bufBands[iBand].buffShort = new short[buftmp[iBand].length];
420
421
            //Escribimos el bloque destino
422
            for (int iBand = 0; iBand < buftmp.length; iBand++)
423
                    for (int i = 0; i < buftmp[iBand].length; i++)
424
                            bufBands[iBand].buffShort[i] = buftmp[iBand][i];
425
426
        for (int iBand = 0; iBand < buftmp.length; iBand++){
427
                try {
428
                                rband = dset_destino.getRasterBand(iBand + 1);
429
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Int16);
430
                } catch (GdalException e) {
431
                                //No se est? escribiendo ...
432
                        }
433
        }
434
    }
435
436
    /**
437
     * Escritura de datos tipo Int.
438
     * @param sizeY Alto del bloque que se escribe.
439
     * @param posicionY Posici?ny a partir desde donde se comienza.
440
     */
441
    public void writeIntBand(int sizeY, int posicionY){
442
            int[][] buftmp = dataWriter.readIntData(sizeWindowX, sizeY);
443
            for(int iBand = 0; iBand < nBands; iBand ++)
444
                bufBands[iBand].buffInt = new int[buftmp[iBand].length];
445
446
            //Escribimos el bloque destino
447
            for (int iBand = 0; iBand < buftmp.length; iBand++)
448
                    for (int i = 0; i < buftmp[iBand].length; i++)
449
                            bufBands[iBand].buffInt[i] = buftmp[iBand][i];
450
451
        for (int iBand = 0; iBand < buftmp.length; iBand++){
452
                try {
453
                                rband = dset_destino.getRasterBand(iBand + 1);
454
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Int32);
455
                } catch (GdalException e) {
456
                                //No se est? escribiendo ...
457
                        }
458
        }
459
    }
460
461
    /**
462
     * Escritura de datos tipo Float.
463
     * @param sizeY Alto del bloque que se escribe.
464
     * @param posicionY Posici?ny a partir desde donde se comienza.
465
     */
466
    public void writeFloatBand(int sizeY, int posicionY){
467
            float[][] buftmp = dataWriter.readFloatData(sizeWindowX, sizeY);
468
            for(int iBand = 0; iBand < nBands; iBand ++)
469
                bufBands[iBand].buffFloat = new float[buftmp[iBand].length];
470
471
            //Escribimos el bloque destino
472
            for (int iBand = 0; iBand < buftmp.length; iBand++)
473
                    for (int i = 0; i < buftmp[iBand].length; i++)
474
                            bufBands[iBand].buffFloat[i] = buftmp[iBand][i];
475
476
        for (int iBand = 0; iBand < buftmp.length; iBand++){
477
                try {
478
                                rband = dset_destino.getRasterBand(iBand + 1);
479
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Float32);
480
                } catch (GdalException e) {
481
                                //No se est? escribiendo ...
482
                        }
483
        }
484
    }
485
486
    /**
487
     * Escritura de datos tipo Double.
488
     * @param sizeY Alto del bloque que se escribe.
489
     * @param posicionY Posici?ny a partir desde donde se comienza.
490
     */
491
    public void writeDoubleBand(int sizeY, int posicionY){
492
            double[][] buftmp = dataWriter.readDoubleData(sizeWindowX, sizeY);
493
            for(int iBand = 0; iBand < nBands; iBand ++)
494
                bufBands[iBand].buffDouble = new double[buftmp[iBand].length];
495
496
            //Escribimos el bloque destino
497
            for (int iBand = 0; iBand < buftmp.length; iBand++)
498
                    for (int i = 0; i < buftmp[iBand].length; i++)
499
                            bufBands[iBand].buffDouble[i] = buftmp[iBand][i];
500
501
        for (int iBand = 0; iBand < buftmp.length; iBand++){
502
                try {
503
                                rband = dset_destino.getRasterBand(iBand + 1);
504
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Float64);
505
                } catch (GdalException e) {
506
                                //No se est? escribiendo ...
507
                        }
508
        }
509
    }
510
    /**
511
     * Escritura para tipo de dato ARGB.
512
     * @param sizeY Alto del bloque que se escribe.
513
     * @param posicionY Posici?ny a partir desde donde se comienza.
514
     */
515
    public void writeARGBBand(int sizeY, int posicionY){
516
            int[] buftmp = dataWriter.readARGBData(sizeWindowX, sizeY, 0);
517
             for(int iBand = 0; iBand < nBands; iBand ++)
518
                 bufBands[iBand].buffByte = new byte[buftmp.length];
519
520
         //Escribimos el bloque destino
521
         for (int i = 0; i < buftmp.length; i++) {
522
             bufBands[0].buffByte[i] = (byte) (((buftmp[i] & 0xff0000) >> 16) &
523
                                    0xff);
524
             bufBands[1].buffByte[i] = (byte) (((buftmp[i] & 0xff00) >> 8) & 0xff);
525
             bufBands[2].buffByte[i] = (byte) ((buftmp[i] & 0xff) & 0xff);
526
         }
527
528
         try {
529
             rband = dset_destino.getRasterBand(1);
530
             rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[0],
531
                               Gdal.GDT_Byte);
532
             rband = dset_destino.getRasterBand(2);
533
             rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[1],
534
                               Gdal.GDT_Byte);
535
             rband = dset_destino.getRasterBand(3);
536
             rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[2],
537
                               Gdal.GDT_Byte);
538
         } catch (GdalException e) {
539
             e.printStackTrace();
540
         }
541
    }
542
543
    /**
544
     * Escribe tres bandas en el GDALRasterBand desde el IDataWriter con una
545
     * altura definida por sizeY.
546
     * @param buftmp        Buffer
547
     * @param sizeY        Altura en pixels del bloque leido
548
     * @param posicionY        Posici?n y a partir de la cual se escribe en el GDALRasterBand destino
549
     */
550
    private void writeBands(int sizeY, int posicionY) {
551
        //leemos el bloque origen
552
553
        switch(dataType){
554
        case RasterBuffer.TYPE_IMAGE:
555
                writeARGBBand(sizeY, posicionY);
556
                break;
557
        case RasterBuffer.TYPE_BYTE:
558
                writeByteBand(sizeY, posicionY);
559
                break;
560
        case RasterBuffer.TYPE_SHORT:
561
                writeShortBand(sizeY, posicionY);
562
                break;
563
        case RasterBuffer.TYPE_INT:
564
                writeIntBand(sizeY, posicionY);
565
                break;
566
        case RasterBuffer.TYPE_FLOAT:
567
                writeFloatBand(sizeY, posicionY);
568
                break;
569
        case RasterBuffer.TYPE_DOUBLE:
570
                writeDoubleBand(sizeY, posicionY);
571
                break;
572
        }
573
    }
574
575
    /**
576
     * Funci?n que gestiona la lectura desde el origen y la escritura
577
     * de Gdal sobre el fichero destino.
578
     * @param mode        Modo de escritura
579
     * @throws IOException
580
     */
581
    private void write(int mode) throws IOException {
582
        buf = new GdalBuffer();
583
        bufBands = new GdalBuffer[nBands];
584
        for(int iBand = 0; iBand < nBands; iBand ++)
585
                bufBands[iBand] = new GdalBuffer();
586
587
       // int[] buftmp = null;
588
589
        //long t1 = System.currentTimeMillis();
590
        //try {
591
            if (mode == Mode.fileWrite) {
592
                /*for (int iBand = 0; iBand < this.nBands; iBand++) {
593
                    rband = dset_destino.getRasterBand(iBand + 1);
594

595
                    for (int iBlock = 0; iBlock < nBlocks; iBlock++) {
596
                            if(write){
597
                                //leemos el bloque origen
598
                                buf.buffByte = currentRaster.getGeoFile().getWindow(0,
599
                                                                                    iBlock * this.support.getBlockSize(),
600
                                                                                    sizeWindowX,
601
                                                                                    this.support.getBlockSize(),
602
                                                                                    iBand +
603
                                                                                    1);
604

605
                                //Escribimos el bloque destino
606
                                rband.writeRaster(0,
607
                                                  iBlock * this.support.getBlockSize(),
608
                                                  sizeWindowX,
609
                                                  this.support.getBlockSize(), buf,
610
                                                  Gdal.GDT_Byte);
611
                            }//else
612
                                    //this.writeClose();
613
                    }
614
                }*/
615
            } else if (mode == Mode.dataWrite) {
616
                //for(int iBlock=1;iBlock<=nBlocks;iBlock++){
617
                for (int iBlock = 0; iBlock < nBlocks; iBlock++) {
618
                    int posicionY = iBlock * this.support.getBlockSize();
619
                    if(write)
620
                            writeBands( this.support.getBlockSize(), posicionY);
621
                    /*else
622
                            this.writeClose();*/
623
                }
624
            }
625
626
            if (anchoResto != 0) {
627
                if (mode == Mode.fileWrite) {
628
                    /*for (int iBand = 0; iBand < this.nBands; iBand++) {
629
                        rband = dset_destino.getRasterBand(iBand + 1);
630
                        if(write){
631
                                //leemos el bloque origen
632
                                buf.buffByte = currentRaster.getGeoFile().getWindow(0,
633
                                                                                    nBlocks * this.support.getBlockSize(),
634
                                                                                    sizeWindowX,
635
                                                                                    anchoResto,
636
                                                                                    iBand +
637
                                                                                    1);
638

639
                                //Escribimos el bloque destino
640
                                rband.writeRaster(0,
641
                                                  nBlocks * this.support.getBlockSize(),
642
                                                  sizeWindowX, anchoResto, buf,
643
                                                  Gdal.GDT_Byte);
644
                        }//else
645
                                //this.writeClose();
646
                    }*/
647
                } else if (mode == Mode.dataWrite) {
648
                    int posicionY = nBlocks * this.support.getBlockSize();
649
                    if(write)
650
                            writeBands(anchoResto, posicionY);
651
                    /*else
652
                            this.writeClose();*/
653
                }
654
            }
655
        /*} catch (GdalException e) {
656
            e.printStackTrace();
657
        }*/
658
    }
659
660
    /**
661
     * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
662
     * @throws IOException
663
     */
664
    public void fileWrite() throws IOException {
665
        /*if (currentRaster == null) {
666
            throw new IOException("No se ha asignado un fichero de entrada.");
667
        }*/
668
669
        this.write(Mode.fileWrite);
670
    }
671
672
    /**
673
     * Realiza una copia en el formato especificado.
674
     * @throws IOException
675
     */
676
    public static void createCopy(GdalDriver driverDst, String dst, String src,
677
                    boolean bstrict, String[] params, IProjection proj) throws IOException, GdalException {
678
        if (dst == null || src == null) {
679
            throw new IOException("No se ha asignado un fichero de entrada.");
680
        }
681
682
        org.gvsig.raster.dataset.io.GdalDriver gdalFile;
683
                try {
684
                        gdalFile = new org.gvsig.raster.dataset.io.GdalDriver(proj, src);
685
                driverDst.createCopy(dst, gdalFile.getNative(), bstrict, params);
686
                if(dst.endsWith(".jpg") || dst.endsWith(".jpeg"))
687
                        GdalWriter.createWorldFile(dst, gdalFile);
688
                gdalFile.close();
689
                } catch (NotSupportedExtensionException e) {
690
                        e.printStackTrace();
691
                }
692
    }
693
694
    /**
695
         * Crea un fichero de georeferenciaci?n
696
         * @param img
697
         * @param name
698
         * @return
699
         * @throws IOException
700
         */
701
        private static void createWorldFile(String name, org.gvsig.raster.dataset.io.GdalDriver gdalFile) throws IOException{
702
            File tfw = null;
703
704
            String extWorldFile = ".wld";
705
            if(name.endsWith("tif"))
706
                    extWorldFile = ".tfw";
707
            if(name.endsWith("jpg") || name.endsWith("jpeg"))
708
                    extWorldFile = ".jpgw";
709
710
            tfw = new File(name.substring(0, name.lastIndexOf(".")) + extWorldFile);
711
712
            //Generamos un world file para gdal
713
            DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(tfw)) );
714
            dos.writeBytes((gdalFile.getExtent().getMax().getX() - gdalFile.getExtent().getMin().getX())/gdalFile.getWidth()+"\n");
715
            dos.writeBytes("0.0\n");
716
            dos.writeBytes("0.0\n");
717
            dos.writeBytes((gdalFile.getExtent().getMax().getY() - gdalFile.getExtent().getMin().getY())/gdalFile.getHeight()+"\n");
718
            dos.writeBytes(""+gdalFile.getExtent().getMin().getX()+"\n");
719
            dos.writeBytes(""+gdalFile.getExtent().getMin().getY()+"\n");
720
            dos.close();
721
        }
722
723
724
    /**
725
     * Realiza la escritura de datos con los datos que le pasa el cliente.
726
     * @throws IOException
727
     */
728
    public void dataWrite() throws IOException {
729
        if (dataWriter == null) {
730
            throw new IOException("No se ha obtenido un objeto de entrada para la escritura valido.");
731
        }
732
733
        this.write(Mode.dataWrite);
734
    }
735
736
    /**
737
     * Cancela el salvado de datos.
738
     * @throws GdalException
739
     */
740
    public void writeClose() {
741
        try {
742
                if(dset_destino != null)
743
                        dset_destino.close();
744
           //oSRS = null;
745
        } catch (GdalException e) {
746
            e.printStackTrace();
747
        }
748
    }
749
750
    /**
751
     * Cancela el salvado de datos.
752
     */
753
    public void writeCancel() {
754
       write = false;
755
    }
756
757
    /**
758
     * Devuelve la configuraci?n de la ventana de dialogo
759
     * para las propiedades del driver de escritura de Gdal.
760
     * @return XML de configuraci?n del dialogo.
761
     */
762
    public String getXMLPropertiesDialog() {
763
        StringBuffer options = null;
764
        options = new StringBuffer();
765
        options.append("<window sizex=\"" + this.windowSizeX + "\" sizey=\"" +
766
                       this.windowSizeY + "\">");
767
        options.append("<panel sizex=\"" + this.panelSizeX + "\" sizey=\"" +
768
                       this.panelSizeY + "\" layout=\"" + this.panelLayout +
769
                       "\" border=\"yes\">");
770
771
        options.append("<panel layout=\"FlowLayout\" position=\"North\" align=\"left\">");
772
        options.append("<label>Block Size:</label>");
773
        options.append("<combo ident=\"BLOCKSIZE\" selected=\"" +
774
                       this.support.getBlockSize() + "\">");
775
776
        for (int i = 0; i < this.support.getBlockSizeList().length; i++)
777
            options.append("<elem>" + this.support.getBlockSizeList()[i] +
778
                           "</elem>");
779
780
        options.append("</combo>");
781
        //options.append("<label>Georef Si/No:</label>");
782
783
        String sel = null;
784
785
        if (this.support.getGeoref()) {
786
            sel = new String("yes");
787
        } else {
788
            sel = new String("no");
789
        }
790
791
        /*options.append("<check ident=\"GEOREF\" selected=\"" + sel +
792
                       "\" text=\"\">");
793
        options.append("</check>");*/
794
        options.append("</panel>");
795
796
        options.append("<panel layout=\"FlowLayout\" position=\"Center\" align=\"left\">");
797
        options.append("<label>Photometric:</label>");
798
        options.append("<combo ident=\"PHOTOMETRIC\" selected=\"" +
799
                       this.support.getPhotometric() + "\">");
800
801
        for (int i = 0; i < this.support.getPhotometricList().length; i++)
802
            options.append("<elem>" + this.support.getPhotometricList()[i] +
803
                           "</elem>");
804
805
        options.append("</combo>");
806
        options.append("<label>Interleave:</label>");
807
        options.append("<combo ident=\"INTERLEAVE\" selected=\"" +
808
                       this.support.getInterleave() + "\">");
809
810
        for (int i = 0; i < this.support.getInterleaveList().length; i++)
811
            options.append("<elem>" + this.support.getInterleaveList()[i] +
812
                           "</elem>");
813
814
        options.append("</combo>");
815
        options.append("</panel>");
816
817
        options.append("<panel layout=\"FlowLayout\" position=\"South\" align=\"left\">");
818
        options.append("<label>Compresi?n:</label>");
819
        options.append("<combo ident=\"COMPRESS\" selected=\"" +
820
                       this.support.getCompress() + "\">");
821
822
        for (int i = 0; i < this.support.getCompressList().length; i++)
823
            options.append("<elem>" + this.support.getCompressList()[i] +
824
                           "</elem>");
825
826
        options.append("</combo>");
827
        options.append("<label>Generar Tfw:</label>");
828
        sel = null;
829
830
        if (this.support.getTfw()) {
831
            sel = new String("yes");
832
        } else {
833
            sel = new String("no");
834
        }
835
836
        options.append("<check ident=\"TFW\" selected=\"" + sel +
837
                       "\" text=\"\">");
838
        options.append("</check>");
839
        options.append("</panel>");
840
841
        options.append("</panel>");
842
        options.append("</window>");
843
844
        return options.toString();
845
    }
846
847
    /**
848
     * Obtiene el valor a la variable write que estar? a true cuando se est? escribiendo
849
     *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
850
     * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
851
     * de salida.
852
     * @return True si puede escribirse y false si no puede
853
     */
854
    public boolean isWrite() {
855
                return write;
856
        }
857
858
    /**
859
     * Asigna el valor a la variable write que estar? a true cuando se est? escribiendo
860
     *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
861
     * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
862
     * de salida.
863
     * @param write Variable booleana. True si puede escribirse y false si no puede
864
     */
865
        public void setWrite(boolean write) {
866
                this.write = write;
867
        }
868
869
        /**
870
         * Obtiene las opciones de salvado.
871
         * @return GdalSupportOptions
872
         */
873
        public GdalSupportOptions getSupport(){
874
            return this.support;
875
    }
876
877
    /**
878
     *
879
     * @author Nacho Brodin (nachobrodin@gmail.com)
880
     *
881
     * Opciones que soporta el driver de escritura de Gdal.
882
     */
883
    public class GdalSupportOptions extends WriterSupportOptions {
884
        private String[]         photometric = {
885
                                           "YCBR", "MINISBLACK", "MINISWHITE",
886
                                           "RGB", "CMYK", "CIELAB", "ICCLAB",
887
                                           "ITULAB", "CBCR"
888
                                       };
889
        private String[]         interleave = { "BAND", "PIXEL" };
890
        private String[]         compress = { "LZW", "PACKBITS", "DEFLATE", "NONE" };
891
        private String                 photometricDefault = "RGB";
892
        private String                 interleaveDefault = "BAND";
893
        private String                 compressDefault = "NONE";
894
895
        private boolean tfw = false;
896
897
        public GdalSupportOptions(String ext) {
898
            super(ext);
899
        }
900
901
        /**
902
         * @param defaultPhot        Tipo de imagen
903
         */
904
        public void setPhotometric(String defaultPhot) {
905
            this.photometricDefault = defaultPhot;
906
        }
907
908
        /**
909
         * @param defaultInt
910
         */
911
        public void setInterleave(String defaultInt) {
912
            this.interleaveDefault = defaultInt;
913
        }
914
915
        /**
916
         * @param defaultComp
917
         */
918
        public void setCompress(String defaultComp) {
919
            this.compressDefault = defaultComp;
920
        }
921
922
        /**
923
         * Asigna true o false si se desea generar un fichero tfw con la
924
         * georeferenciaci?n o no;
925
         * @param tfw true se genera el fichero tfw y false no se genera
926
         */
927
        public void setTfw(boolean tfw) {
928
            this.tfw = tfw;
929
        }
930
931
        /**
932
         * @return
933
         */
934
        public String[] getPhotometricList() {
935
            return photometric;
936
        }
937
938
        /**
939
         * @return
940
         */
941
        public String[] getInterleaveList() {
942
            return interleave;
943
        }
944
945
        /**
946
         * @return
947
         */
948
        public String[] getCompressList() {
949
            return compress;
950
        }
951
952
        /**
953
         * @return
954
         */
955
        public String getPhotometric() {
956
            return photometricDefault;
957
        }
958
959
        /**
960
         * @return
961
         */
962
        public String getInterleave() {
963
            return interleaveDefault;
964
        }
965
966
        /**
967
         * Obtiene el par?metro de compresi?n
968
         * @return
969
         */
970
        public String getCompress() {
971
            return compressDefault;
972
        }
973
974
        /**
975
         * Devuelve true o false si se genera un fichero tfw con la
976
         * georeferenciaci?n o no;
977
         * @param tfw true se genera el fichero tfw y false no se genera
978
         */
979
        public boolean getTfw() {
980
            return tfw;
981
        }
982
    }
983
984
    private class Mode {
985
        public final static int fileWrite = 0;
986
        public final static int dataWrite = 1;
987
    }
988
}