Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libRaster / src / org / gvsig / raster / dataset / io / GdalWriter.java @ 17599

History | View | Annotate | Download (22.8 KB)

1
/* 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.awt.geom.AffineTransform;
22
import java.awt.geom.Point2D;
23
import java.io.IOException;
24
import java.util.ArrayList;
25

    
26
import org.cresques.cts.IProjection;
27
import org.gvsig.raster.RasterLibrary;
28
import org.gvsig.raster.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.Params;
33
import org.gvsig.raster.dataset.Params.Param;
34
import org.gvsig.raster.dataset.io.features.BMPFeatures;
35
import org.gvsig.raster.dataset.io.features.GTiffFeatures;
36
import org.gvsig.raster.dataset.io.features.HFAFeatures;
37
import org.gvsig.raster.dataset.io.features.IDRISIFeatures;
38
import org.gvsig.raster.dataset.io.features.ILWIS_MprFeatures;
39
import org.gvsig.raster.dataset.io.features.PNM_PgmFeatures;
40
import org.gvsig.raster.dataset.io.features.PNM_PpmFeatures;
41
import org.gvsig.raster.dataset.io.features.WriteFileFormatFeatures;
42
import org.gvsig.raster.process.RasterTask;
43
import org.gvsig.raster.process.RasterTaskQueue;
44
import org.gvsig.raster.util.RasterUtilities;
45
import org.gvsig.raster.util.extensionPoints.ExtensionPoints;
46
import org.gvsig.raster.util.extensionPoints.ExtensionPointsSingleton;
47

    
48
import es.gva.cit.jecwcompress.EcwException;
49
import es.gva.cit.jgdal.Gdal;
50
import es.gva.cit.jgdal.GdalBuffer;
51
import es.gva.cit.jgdal.GdalException;
52
import es.gva.cit.jgdal.GdalRasterBand;
53
import es.gva.cit.jgdal.GeoTransform;
54

    
55

    
56
/**
57
 * Driver para la escritura a trav?s de Gdal.
58
 * Puede exportar un fichero de un formato a otro desde un GeoRasterFile
59
 * en cualquier formato soportado por la lectura a un formato que este incluido
60
 * en la lista supportedDrv.
61
 *
62
 * Puede salvar a disco en un formato que este incluido en la lista supportedDrv
63
 * obteniendo los datos que van siendo servidos desde el cliente. Este cliente
64
 * debe implementar un IDataWriter o tener un objeto que lo implemente. Inicialmente
65
 * le pasar? los par?metros de la imagen de salida y cuando el driver comience a
66
 * escribir le ir? solicitando m?s a trav?s del m?todo readData de IDataWriter.
67
 * El cliente ser? el que lleve el control de lo que va sirviendo y lo que le queda
68
 * por servir.
69
 * @author Nacho Brodin (nachobrodin@gmail.com)
70
 */
71
public class GdalWriter extends GeoRasterWriter {
72

    
73
        public static void register() {
74
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
75

    
76
                extensionPoints.add("RasterWriter", "tif", GdalWriter.class);
77
                fileFeature.put("tif", new GTiffFeatures());
78

    
79
                extensionPoints.add("RasterWriter", "img", GdalWriter.class);
80
                fileFeature.put("img", new HFAFeatures());
81

    
82
                extensionPoints.add("RasterWriter", "bmp", GdalWriter.class);
83
                fileFeature.put("bmp", new BMPFeatures());
84

    
85
                extensionPoints.add("RasterWriter", "pgm", GdalWriter.class);
86
                fileFeature.put("pgm", new PNM_PgmFeatures());
87

    
88
                extensionPoints.add("RasterWriter", "ppm", GdalWriter.class);
89
                fileFeature.put("ppm", new PNM_PpmFeatures());
90

    
91
                extensionPoints.add("RasterWriter", "mpl", GdalWriter.class);
92
                fileFeature.put("mpl", new ILWIS_MprFeatures());
93

    
94
                extensionPoints.add("RasterWriter", "rst", GdalWriter.class);
95
                fileFeature.put("rst", new IDRISIFeatures());
96

    
97
                //La exportaci?n no es correcta del todo
98
                //extensionPoints.add("RasterWriter", "rmf", GdalWriter.class);
99
                //fileFeature.put("rmf", new RMFFeatures());
100

    
101
                //No salva datos. Siempre sale negra la imagen
102
                //extensionPoints.add("RasterWriter", "aux", GdalWriter.class);
103
                //fileFeature.put("aux", new PAuxFeatures());
104
        }
105

    
106
        private es.gva.cit.jgdal.GdalDriver                drv;
107
        private Gdal                                                         dstDataset = null;
108
        private GdalRasterBand                                         rband = null;
109
        private GeoTransform                                         geot = null; //Datos de georeferenciaci?n
110
        //private OGRSpatialReference                         oSRS; //Datos de proyecci?n
111
        private GdalBuffer[]                                        bufBands = null;
112
        private int                                                         nBlocks = 0; //N?mero de bloques en Y en el que se divide la imagen para escribir
113
        private int                                                         anchoResto = 0; //Tama?o del ?ltimo bloque de la imagen.
114
        private boolean                                                        write = true; //Cuando est? a true se puede escribir en la imagen de salida. Si est? a false el proceso es interrumpido
115
        private int                                                         dataType = RasterBuffer.TYPE_UNDEFINED;
116

    
117
        /**
118
         * Carga los par?metros de este driver.
119
         */
120
        public void loadParams(String ident) {
121
                WriteFileFormatFeatures wfff = (WriteFileFormatFeatures)fileFeature.get(ident);
122
                wfff.loadParams();
123
                driverParams = wfff.getParams();
124
        }
125

    
126
        /**
127
         * Constructor para la obtenci?n de par?metros del driver
128
         * @param drvType        Tipo de driver
129
         */
130
        public GdalWriter(String fileName) {
131
                ident = RasterUtilities.getExtensionFromFileName(fileName);
132
                driver = ((WriteFileFormatFeatures)fileFeature.get(ident)).getDriverName();
133

    
134
                loadParams(ident);
135
        }
136

    
137
        /**
138
         * Constructor para salvar datos servidos por el cliente
139
         * @param dataWriter               Objeto servidor de datos para el driver de escritura
140
         * @param outFilename              Fichero de salida
141
         * @param blockSize                Tama?o de bloque
142
         * @param Extent                   extent
143
         * @param compresion                   Compresi?n si la tiene
144
         * @param outSizeX                          Tama?o de salida en X
145
         * @param outSizeY                        Tama?o de salida en Y
146
         * @param dataType                        Tipo de dato
147
         * @throws GdalException
148
         * @throws IOException
149
         */
150
        public GdalWriter(        IDataWriter dataWriter,
151
                        String outFileName,
152
                        Integer nBands,
153
                        AffineTransform at,
154
                        Integer outSizeX,
155
                        Integer outSizeY,
156
                        Integer dataType,
157
                        Params params, 
158
                        IProjection proj) throws GdalException, IOException {
159
                this(dataWriter, outFileName, nBands, at, outSizeX, outSizeY, dataType, params, proj, new Boolean(true));
160
        }
161
        
162
        /**
163
         * Constructor para salvar datos servidos por el cliente
164
         * @param dataWriter               Objeto servidor de datos para el driver de escritura
165
         * @param outFilename              Fichero de salida
166
         * @param blockSize                Tama?o de bloque
167
         * @param Extent                   extent
168
         * @param compresion                   Compresi?n si la tiene
169
         * @param outSizeX                          Tama?o de salida en X
170
         * @param outSizeY                        Tama?o de salida en Y
171
         * @param dataType                        Tipo de dato
172
         * @param geo                                Flag que dice si se salva con georreferenciaci?n o sin ella
173
         * @throws GdalException
174
         * @throws IOException
175
         */
176
        public GdalWriter(        IDataWriter dataWriter,
177
                        String outFileName,
178
                        Integer nBands,
179
                        AffineTransform at,
180
                        Integer outSizeX,
181
                        Integer outSizeY,
182
                        Integer dataType,
183
                        Params params, 
184
                        IProjection proj, 
185
                        Boolean geo)throws GdalException, IOException {
186
                
187
                this.proj = proj;
188
                ident = outFileName.toLowerCase().substring(outFileName.lastIndexOf(".") + 1);
189
                driver = ((WriteFileFormatFeatures)fileFeature.get(ident)).getDriverName();
190
                this.dataType = dataType.intValue();
191
                this.at = at;
192
                percent = 0;
193

    
194
                this.dataWriter = dataWriter;
195
                this.outFileName = outFileName;
196

    
197
                this.sizeWindowX = outSizeX.intValue();
198
                this.sizeWindowY = outSizeY.intValue();
199

    
200
                if ((sizeWindowX < 0) || (sizeWindowY < 0))
201
                        throw new IOException("Tama?o del fichero de salida erroneo.");
202

    
203
                this.nBands = nBands.intValue();
204

    
205
                //Calculamos la georeferenciaci?n a partir del extend pasado por el cliente.
206

    
207
                geot = new GeoTransform();
208
                geot.adfgeotransform[0] = at.getTranslateX();
209
                geot.adfgeotransform[3] = at.getTranslateY(); 
210
                geot.adfgeotransform[1] = at.getScaleX();
211
                geot.adfgeotransform[5] = at.getScaleY();
212
                geot.adfgeotransform[2] = at.getShearX();
213
                geot.adfgeotransform[4] = at.getShearY();
214
                
215
                String outRmf = outFileName.substring(0, outFileName.lastIndexOf("."));
216
                if(geo.booleanValue())
217
                        RasterUtilities.saveGeoInfo(outRmf, at, new Point2D.Double(sizeWindowX, sizeWindowY));
218

    
219
                if(params == null)
220
                        loadParams(ident);
221
                else
222
                        this.driverParams = params;
223

    
224
                init();
225
        }
226

    
227
        /**
228
         * A?ade la proyecci?n Wkt con la que salvar.
229
         * @param wkt
230
         * @throws GdalException
231
         */
232
        public void setWkt(String wkt) {
233
                if(dstDataset != null && wkt != null && wkt.compareTo("unknown") != 0) {
234
                        try {
235
                                dstDataset.setProjection(wkt);
236
                        } catch (GdalException e) {
237
                                System.err.println("Proyecci?n Wkt no asignada en GdalWriter");
238
                                return;
239
                        }
240
                }
241
        }
242
        
243
        /**
244
         * Asigna el tipo de driver con el que se salvar? la imagen
245
         * @param drvType        Tipo de driver
246
         */
247
        public void setDriverType(String drvType) {
248
                this.driver = drvType;
249
        }
250

    
251
        /**
252
         * Creaci?n del dataset de destino.
253
         * @throws EcwException
254
         */
255
        private void init() throws GdalException {
256
                //Controlamos que el tipo de driver sea correcto
257
                if (driver == null) {
258
                        throw new GdalException("Tipo de driver sin especificar.");
259
                }
260

    
261
                boolean okdrvtype = false;
262

    
263
                String[] types = GeoRasterWriter.getDriversType();
264
                for (int i = 0; i < GeoRasterWriter.getNTypes(); i++)
265
                        if (driver.equals(types[i]))
266
                                okdrvtype = true;
267

    
268
                if (okdrvtype == false)
269
                        throw new GdalException("El tipo de driver " + driver + " no est? soportado por GdalWriter.");
270

    
271
                //Obtenemos el driver y creamos el dataset del destino
272
                drv = Gdal.getDriverByName(driver);
273

    
274
                if (dstDataset != null) {
275
                        dstDataset.close();
276
                        dstDataset = null;
277
                }
278

    
279
                dstDataset = drv.create(outFileName, sizeWindowX, sizeWindowY,
280
                                nBands, RasterUtilities.getGdalTypeFromRasterBufType(dataType), gdalParamsFromRasterParams(driverParams));
281

    
282
                dstDataset.setGeoTransform(geot);
283

    
284
                int blockSize = RasterLibrary.blockHeight;
285
                
286
                nBlocks = (int) (sizeWindowY / blockSize);
287
                anchoResto = sizeWindowY - (nBlocks * blockSize);
288
        }
289

    
290
        public void anotherFile(String fileName)throws GdalException {
291
                dstDataset = drv.create(fileName, sizeWindowX, sizeWindowY,
292
                                nBands, RasterUtilities.getGdalTypeFromRasterBufType(dataType), gdalParamsFromRasterParams(driverParams));
293
        }
294

    
295
        /**
296
         * Convierte los par?metros obtenidos desde el objeto params a parametros
297
         * comprensibles por la librer?a gdal
298
         * @param p Params
299
         * @return Array de par?metros
300
         */
301
        public String[] gdalParamsFromRasterParams(Params p) {
302
                if(p == null)
303
                        return null;
304
                ArrayList paramList = new ArrayList();
305
                Param phot = (Param)p.getParamById("photometric");
306
                if(phot != null)
307
                        paramList.add("PHOTOMETRIC=" + phot.list[((Integer)phot.defaultValue).intValue()]);
308
                Param inter = (Param)p.getParamById("interleave");
309
                if(inter != null)
310
                        paramList.add("INTERLEAVE=" + inter.list[((Integer)inter.defaultValue).intValue()]);
311
                Param comp = (Param)p.getParamById("compression");//GIF LZW, ...
312
                if(comp != null)
313
                        paramList.add("COMPRESS=" + comp.list[((Integer)comp.defaultValue).intValue()]);
314
                Param comp1 = (Param)p.getParamById("compress"); //HFA (YES, NO)
315
                if(comp1 != null)
316
                        paramList.add("COMPRESS=" + comp1.list[((Integer)comp1.defaultValue).intValue()]);
317
                Param rrd = (Param)p.getParamById("rrd");
318
                if(rrd != null)
319
                        paramList.add("HFA_USE_RRD=" + rrd.list[((Integer)rrd.defaultValue).intValue()]);
320
                Param mtw = (Param)p.getParamById("Mtw");
321
                if(mtw != null)
322
                        paramList.add("MTW=" + mtw.list[((Integer)mtw.defaultValue).intValue()]);
323
                Param tw = (Param)p.getParamById("Tile Width");
324
                if(tw != null)
325
                        paramList.add("BLOCKXSIZE=" + tw.list[((Integer)tw.defaultValue).intValue()]);
326
                Param th = (Param)p.getParamById("Tile Height");
327
                if(th != null)
328
                        paramList.add("BLOCKYSIZE=" + th.list[((Integer)th.defaultValue).intValue()]);
329
                Param qt = (Param)p.getParamById("quality");
330
                if(qt != null)
331
                        paramList.add("QUALITY=" + qt.defaultValue);
332
                Param prog = (Param)p.getParamById("progressive");
333
                if(prog != null)
334
                        paramList.add("PROGRESSIVE=" + prog.defaultValue);
335
                
336
                if(paramList.size() == 0)
337
                        return null;
338

    
339
                String[] result = new String[paramList.size()];
340
                for (int i = 0; i < result.length; i++)
341
                        result[i] = (String)paramList.get(i);
342
                return result;
343
        }
344

    
345
        /**
346
         * Escritura de datos tipo Byte.
347
         * @param sizeY Alto del bloque que se escribe.
348
         * @param posicionY Posici?ny a partir desde donde se comienza.
349
         */
350
        public void writeByteBand(int sizeY, int posicionY) {
351
                byte[][] buftmp = dataWriter.readByteData(sizeWindowX, sizeY);
352
                for(int iBand = 0; iBand < nBands; iBand ++)
353
                        bufBands[iBand].buffByte = new byte[buftmp[iBand].length];
354

    
355
                //Escribimos el bloque destino
356
                for (int iBand = 0; iBand < buftmp.length; iBand++)
357
                        for (int i = 0; i < buftmp[iBand].length; i++)
358
                                bufBands[iBand].buffByte[i] = buftmp[iBand][i];
359

    
360
                for (int iBand = 0; iBand < buftmp.length; iBand++){
361
                        try {
362
                                rband = dstDataset.getRasterBand(iBand + 1);
363
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Byte);
364
                        } catch (GdalException e) {
365
                                //No se est? escribiendo ...
366
                        }
367
                }
368
        }
369

    
370
        /**
371
         * Escritura de datos tipo Short.
372
         * @param sizeY Alto del bloque que se escribe.
373
         * @param posicionY Posici?ny a partir desde donde se comienza.
374
         */
375
        public void writeShortBand(int sizeY, int posicionY) {
376
                short[][] buftmp = dataWriter.readShortData(sizeWindowX, sizeY);
377
                for(int iBand = 0; iBand < nBands; iBand ++)
378
                        bufBands[iBand].buffShort = new short[buftmp[iBand].length];
379

    
380
                //Escribimos el bloque destino
381
                for (int iBand = 0; iBand < nBands; iBand++)
382
                        for (int i = 0; i < buftmp[iBand].length; i++)
383
                                bufBands[iBand].buffShort[i] = buftmp[iBand][i];
384

    
385
                for (int iBand = 0; iBand < nBands; iBand++){
386
                        try {
387
                                rband = dstDataset.getRasterBand(iBand + 1);
388
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Int16);
389
                        } catch (GdalException e) {
390
                                //No se est? escribiendo ...
391
                        }
392
                }
393
        }
394

    
395
        /**
396
         * Escritura de datos tipo Int.
397
         * @param sizeY Alto del bloque que se escribe.
398
         * @param posicionY Posici?ny a partir desde donde se comienza.
399
         */
400
        public void writeIntBand(int sizeY, int posicionY) {
401
                int[][] buftmp = dataWriter.readIntData(sizeWindowX, sizeY);
402
                for(int iBand = 0; iBand < nBands; iBand ++)
403
                        bufBands[iBand].buffInt = new int[buftmp[iBand].length];
404

    
405
                //Escribimos el bloque destino
406
                for (int iBand = 0; iBand < buftmp.length; iBand++)
407
                        for (int i = 0; i < buftmp[iBand].length; i++)
408
                                bufBands[iBand].buffInt[i] = buftmp[iBand][i];
409

    
410
                for (int iBand = 0; iBand < buftmp.length; iBand++){
411
                        try {
412
                                rband = dstDataset.getRasterBand(iBand + 1);
413
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Int32);
414
                        } catch (GdalException e) {
415
                                //No se est? escribiendo ...
416
                        }
417
                }
418
        }
419

    
420
        /**
421
         * Escritura de datos tipo Float.
422
         * @param sizeY Alto del bloque que se escribe.
423
         * @param posicionY Posici?ny a partir desde donde se comienza.
424
         */
425
        public void writeFloatBand(int sizeY, int posicionY) {
426
                float[][] buftmp = dataWriter.readFloatData(sizeWindowX, sizeY);
427
                for(int iBand = 0; iBand < nBands; iBand ++)
428
                        bufBands[iBand].buffFloat = new float[buftmp[iBand].length];
429

    
430
                //Escribimos el bloque destino
431
                for (int iBand = 0; iBand < buftmp.length; iBand++)
432
                        for (int i = 0; i < buftmp[iBand].length; i++)
433
                                bufBands[iBand].buffFloat[i] = buftmp[iBand][i];
434

    
435
                for (int iBand = 0; iBand < buftmp.length; iBand++){
436
                        try {
437
                                rband = dstDataset.getRasterBand(iBand + 1);
438
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Float32);
439
                        } catch (GdalException e) {
440
                                //No se est? escribiendo ...
441
                        }
442
                }
443
        }
444

    
445
        /**
446
         * Escritura de datos tipo Double.
447
         * @param sizeY Alto del bloque que se escribe.
448
         * @param posicionY Posici?ny a partir desde donde se comienza.
449
         */
450
        public void writeDoubleBand(int sizeY, int posicionY) {
451
                double[][] buftmp = dataWriter.readDoubleData(sizeWindowX, sizeY);
452
                for(int iBand = 0; iBand < nBands; iBand ++)
453
                        bufBands[iBand].buffDouble = new double[buftmp[iBand].length];
454

    
455
                //Escribimos el bloque destino
456
                for (int iBand = 0; iBand < buftmp.length; iBand++)
457
                        for (int i = 0; i < buftmp[iBand].length; i++)
458
                                bufBands[iBand].buffDouble[i] = buftmp[iBand][i];
459

    
460
                for (int iBand = 0; iBand < buftmp.length; iBand++){
461
                        try {
462
                                rband = dstDataset.getRasterBand(iBand + 1);
463
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Float64);
464
                        } catch (GdalException e) {
465
                                //No se est? escribiendo ...
466
                        }
467
                }
468
        }
469
        /**
470
         * Escritura para tipo de dato ARGB.
471
         * @param sizeY Alto del bloque que se escribe.
472
         * @param posicionY Posici?ny a partir desde donde se comienza.
473
         */
474
        public void writeARGBBand(int sizeY, int posicionY) {
475
                int[] buftmp = dataWriter.readARGBData(sizeWindowX, sizeY, 0);
476
                for(int iBand = 0; iBand < nBands; iBand ++)
477
                        bufBands[iBand].buffByte = new byte[buftmp.length];
478

    
479
                //Escribimos el bloque destino
480
                for (int i = 0; i < buftmp.length; i++) {
481
                        bufBands[0].buffByte[i] = (byte) (((buftmp[i] & 0xff0000) >> 16) &
482
                                        0xff);
483
                        bufBands[1].buffByte[i] = (byte) (((buftmp[i] & 0xff00) >> 8) & 0xff);
484
                        bufBands[2].buffByte[i] = (byte) ((buftmp[i] & 0xff) & 0xff);
485
                }
486

    
487
                try {
488
                        rband = dstDataset.getRasterBand(1);
489
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[0],
490
                                        Gdal.GDT_Byte);
491
                        rband = dstDataset.getRasterBand(2);
492
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[1],
493
                                        Gdal.GDT_Byte);
494
                        rband = dstDataset.getRasterBand(3);
495
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[2],
496
                                        Gdal.GDT_Byte);
497
                } catch (GdalException e) {
498
                        e.printStackTrace();
499
                }
500
        }
501

    
502
        /**
503
         * Escribe tres bandas en el GDALRasterBand desde el IDataWriter con una
504
         * altura definida por sizeY.
505
         * @param buftmp        Buffer
506
         * @param sizeY        Altura en pixels del bloque leido
507
         * @param posicionY        Posici?n y a partir de la cual se escribe en el GDALRasterBand destino
508
         */
509
        private void writeBands(int sizeY, int posicionY) {
510
                //leemos el bloque origen
511

    
512
                switch(dataType){
513
                case RasterBuffer.TYPE_IMAGE:
514
                        writeARGBBand(sizeY, posicionY);
515
                        break;
516
                case RasterBuffer.TYPE_BYTE:
517
                        writeByteBand(sizeY, posicionY);
518
                        break;
519
                case RasterBuffer.TYPE_SHORT:
520
                        writeShortBand(sizeY, posicionY);
521
                        break;
522
                case RasterBuffer.TYPE_INT:
523
                        writeIntBand(sizeY, posicionY);
524
                        break;
525
                case RasterBuffer.TYPE_FLOAT:
526
                        writeFloatBand(sizeY, posicionY);
527
                        break;
528
                case RasterBuffer.TYPE_DOUBLE:
529
                        writeDoubleBand(sizeY, posicionY);
530
                        break;
531
                }
532
        }
533

    
534
        /**
535
         * Funci?n que gestiona la lectura desde el origen y la escritura
536
         * de Gdal sobre el fichero destino.
537
         * @param mode        Modo de escritura
538
         * @throws IOException
539
         */
540
        private void write(int mode) throws IOException, InterruptedException {
541
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
542
                
543
                bufBands = new GdalBuffer[nBands];
544
                for(int iBand = 0; iBand < nBands; iBand ++)
545
                        bufBands[iBand] = new GdalBuffer();
546

    
547
                int blockSize = RasterLibrary.blockHeight;
548
                
549
                percent = 0;
550
                nBlocks = (int) (sizeWindowY / blockSize);
551
                int increment = (blockSize * 100) / sizeWindowY;
552
                
553
                if (mode == GeoRasterWriter.MODE_DATAWRITE) {
554
                        for (int iBlock = 0; iBlock < nBlocks; iBlock++) {
555
                                if(task.getEvent() != null)
556
                                        task.manageEvent(task.getEvent());
557
                                int posicionY = iBlock * blockSize;
558
                                if(write)
559
                                        writeBands( blockSize, posicionY);
560
                                percent = (iBlock + 1) * increment;
561
                        }
562
                }
563

    
564
                if (anchoResto != 0) {
565
                        if (mode == GeoRasterWriter.MODE_DATAWRITE) {
566
                                if(task.getEvent() != null)
567
                                        task.manageEvent(task.getEvent());
568
                                int posicionY = nBlocks * blockSize;
569
                                if(write)
570
                                        writeBands(anchoResto, posicionY);
571
                                percent = nBlocks * increment;
572
                        }
573
                }
574

    
575
        }
576

    
577
        /**
578
         * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
579
         * @throws IOException
580
         */
581
        public void fileWrite() throws IOException, InterruptedException {
582
                write(GeoRasterWriter.MODE_FILEWRITE);
583
        }
584

    
585
        /**
586
         * Realiza una copia en el formato especificado.
587
         * @throws IOException
588
         */
589
        public static void createCopy(es.gva.cit.jgdal.GdalDriver driverDst, String dst, String src,
590
                        boolean bstrict, String[] params, IProjection proj) throws IOException, GdalException {
591
                if (dst == null || src == null) 
592
                        throw new IOException("No se ha asignado un fichero de entrada.");
593
                
594
                GdalDriver gdalFile;
595
                try {
596
                        gdalFile = new GdalDriver(proj, src);
597
                        driverDst.createCopy(dst, gdalFile.getNative(), bstrict, params);
598
                        if(        dst.endsWith(".jpg") || 
599
                                dst.endsWith(".jpeg") ||
600
                                dst.endsWith(".png"))
601
                                RasterUtilities.createWorldFile(dst, gdalFile.getExtent(), gdalFile.getWidth(), gdalFile.getHeight());
602
                        gdalFile.close();
603
                } catch (NotSupportedExtensionException e) {
604
                        e.printStackTrace();
605
                }
606
        }
607
        
608
        /**
609
         * Realiza la escritura de datos con los datos que le pasa el cliente.
610
         * @throws IOException
611
         */
612
        public void dataWrite() throws IOException, InterruptedException {
613
                if (dataWriter == null)
614
                        throw new IOException("No se ha obtenido un objeto de entrada para la escritura valido.");
615

    
616
                write(GeoRasterWriter.MODE_DATAWRITE);
617

    
618
                if(        driverParams.getParamById("tfw") != null &&
619
                        driverParams.getParamById("tfw").defaultValue instanceof Boolean && 
620
                        ((Boolean)driverParams.getParamById("tfw").defaultValue).booleanValue() == true) {
621
                        if(at != null)
622
                                RasterUtilities.createWorldFile(this.outFileName, at, sizeWindowX, sizeWindowY);
623
                }
624
        }
625

    
626
        /**
627
         * Cancela el salvado de datos.
628
         * @throws GdalException
629
         */
630
        public void writeClose() {
631
                try {
632
                        if(dstDataset != null)
633
                                dstDataset.close();
634
                } catch (GdalException e) {
635
                        e.printStackTrace();
636
                }
637
        }
638

    
639
        /**
640
         * Cancela el salvado de datos.
641
         */
642
        public void writeCancel() {
643
                write = false;
644
        }
645

    
646
        /**
647
         * Obtiene el valor a la variable write que estar? a true cuando se est? escribiendo
648
         *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
649
         * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
650
         * de salida.
651
         * @return True si puede escribirse y false si no puede
652
         */
653
        public boolean isWrite() {
654
                return write;
655
        }
656

    
657
        /**
658
         * Asigna el valor a la variable write que estar? a true cuando se est? escribiendo
659
         *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
660
         * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
661
         * de salida.
662
         * @param write Variable booleana. True si puede escribirse y false si no puede
663
         */
664
        public void setWrite(boolean write) {
665
                this.write = write;
666
        }
667

    
668
        /**
669
         * Asigna los par?metros del driver modificados por el cliente.
670
         * @param Params
671
         */
672
        public void setParams(Params params) {
673
                this.driverParams = params;
674

    
675
                int blockSize = 256;
676
                try {
677
                        Param param = driverParams.getParamById("blocksize");
678
                        blockSize = Integer.parseInt(param.list[((Integer)param.defaultValue).intValue()]);
679
                        nBlocks = (int) (sizeWindowY / blockSize);
680
                        anchoResto = sizeWindowY - (nBlocks * blockSize);
681
                }catch(NumberFormatException e) {
682
                        //Se queda con el valor de inicializaci?n
683
                }
684
        }
685
}