Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / libraries / libRaster_io / src / org / gvsig / fmap / dal / coverage / dataset / io / GdalWriter.java @ 29713

History | View | Annotate | Download (23.3 KB)

1 28287 nbrodin
/* 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.fmap.dal.coverage.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.fmap.dal.coverage.dataset.io.features.BMPFeatures;
28
import org.gvsig.fmap.dal.coverage.dataset.io.features.GTiffFeatures;
29
import org.gvsig.fmap.dal.coverage.dataset.io.features.HFAFeatures;
30
import org.gvsig.fmap.dal.coverage.dataset.io.features.IDRISIFeatures;
31
import org.gvsig.fmap.dal.coverage.dataset.io.features.ILWIS_MprFeatures;
32
import org.gvsig.fmap.dal.coverage.dataset.io.features.PNM_PgmFeatures;
33
import org.gvsig.fmap.dal.coverage.dataset.io.features.PNM_PpmFeatures;
34
import org.gvsig.raster.RasterLibrary;
35
import org.gvsig.raster.buffer.RasterBuffer;
36
import org.gvsig.raster.dataset.GeoRasterWriter;
37
import org.gvsig.raster.dataset.IDataWriter;
38
import org.gvsig.raster.dataset.NotSupportedExtensionException;
39
import org.gvsig.raster.dataset.Params;
40
import org.gvsig.raster.dataset.RasterDataset;
41
import org.gvsig.raster.dataset.WriteFileFormatFeatures;
42
import org.gvsig.raster.dataset.Params.Param;
43
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
44
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
45
import org.gvsig.raster.process.RasterTask;
46
import org.gvsig.raster.process.RasterTaskQueue;
47
import org.gvsig.raster.util.RasterUtilities;
48
import org.gvsig.tools.ToolsLocator;
49
import org.gvsig.tools.extensionpoint.ExtensionPoint;
50
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
51
52
import es.gva.cit.jecwcompress.EcwException;
53
import es.gva.cit.jgdal.Gdal;
54
import es.gva.cit.jgdal.GdalBuffer;
55
import es.gva.cit.jgdal.GdalException;
56
import es.gva.cit.jgdal.GdalRasterBand;
57
import es.gva.cit.jgdal.GeoTransform;
58
59
60
/**
61
 * Driver para la escritura a trav?s de Gdal.
62
 * Puede exportar un fichero de un formato a otro desde un GeoRasterFile
63
 * en cualquier formato soportado por la lectura a un formato que este incluido
64
 * en la lista supportedDrv.
65
 *
66
 * Puede salvar a disco en un formato que este incluido en la lista supportedDrv
67
 * obteniendo los datos que van siendo servidos desde el cliente. Este cliente
68
 * debe implementar un IDataWriter o tener un objeto que lo implemente. Inicialmente
69
 * le pasar? los par?metros de la imagen de salida y cuando el driver comience a
70
 * escribir le ir? solicitando m?s a trav?s del m?todo readData de IDataWriter.
71
 * El cliente ser? el que lleve el control de lo que va sirviendo y lo que le queda
72
 * por servir.
73
 * @author Nacho Brodin (nachobrodin@gmail.com)
74
 */
75
public class GdalWriter extends GeoRasterWriter {
76
77
        public static void register() {
78 28445 nbrodin
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
79
                ExtensionPoint point = extensionPoints.get("RasterWriter");
80 28287 nbrodin
81
                point.append("tif", "", GdalWriter.class);
82
                fileFeature.put("tif", new GTiffFeatures());
83
84
                point.append("img", "", GdalWriter.class);
85
                fileFeature.put("img", new HFAFeatures());
86
87
                point.append("bmp", "", GdalWriter.class);
88
                fileFeature.put("bmp", new BMPFeatures());
89
90
                point.append("pgm", "", GdalWriter.class);
91
                fileFeature.put("pgm", new PNM_PgmFeatures());
92
93
                point.append("ppm", "", GdalWriter.class);
94
                fileFeature.put("ppm", new PNM_PpmFeatures());
95
96
                point.append("mpl", "", GdalWriter.class);
97
                fileFeature.put("mpl", new ILWIS_MprFeatures());
98
99
                point.append("rst", "", GdalWriter.class);
100
                fileFeature.put("rst", new IDRISIFeatures());
101
102
                //La exportaci?n no es correcta del todo
103
                //point.register("rmf", GdalWriter.class);
104
                //fileFeature.put("rmf", new RMFFeatures());
105
106
                //No salva datos. Siempre sale negra la imagen
107
                //point.register("aux", GdalWriter.class);
108
                //fileFeature.put("aux", new PAuxFeatures());
109
        }
110
111
        private es.gva.cit.jgdal.GdalDriver                drv;
112
        private Gdal                                                         dstDataset = null;
113
        private GdalRasterBand                                         rband = null;
114
        private GeoTransform                                         geot = null; //Datos de georeferenciaci?n
115
        //private OGRSpatialReference                         oSRS; //Datos de proyecci?n
116
        private GdalBuffer[]                                        bufBands = null;
117
        private int                                                         nBlocks = 0; //N?mero de bloques en Y en el que se divide la imagen para escribir
118
        private int                                                         anchoResto = 0; //Tama?o del ?ltimo bloque de la imagen.
119
        private boolean                                                        write = true; //Cuando est? a true se puede escribir en la imagen de salida. Si est? a false el proceso es interrumpido
120
        private int                                                         dataType = RasterBuffer.TYPE_UNDEFINED;
121
122
        /**
123
         * Carga los par?metros de este driver.
124
         */
125
        public void loadParams(String ident) {
126
                WriteFileFormatFeatures wfff = (WriteFileFormatFeatures)fileFeature.get(ident);
127
                wfff.loadParams();
128
                driverParams = wfff.getParams();
129
        }
130
131
        /**
132
         * Constructor para la obtenci?n de par?metros del driver
133
         * @param drvType        Tipo de driver
134
         */
135
        public GdalWriter(String fileName) {
136
                ident = RasterUtilities.getExtensionFromFileName(fileName);
137
                driver = ((WriteFileFormatFeatures)fileFeature.get(ident)).getDriverName();
138
139
                loadParams(ident);
140
        }
141
142
        /**
143
         * Constructor para salvar datos servidos por el cliente
144
         * @param dataWriter               Objeto servidor de datos para el driver de escritura
145
         * @param outFilename              Fichero de salida
146
         * @param blockSize                Tama?o de bloque
147
         * @param Extent                   extent
148
         * @param compresion                   Compresi?n si la tiene
149
         * @param outSizeX                          Tama?o de salida en X
150
         * @param outSizeY                        Tama?o de salida en Y
151
         * @param dataType                        Tipo de dato
152
         * @throws GdalException
153
         * @throws IOException
154
         */
155
        public GdalWriter(        IDataWriter dataWriter,
156
                        String outFileName,
157
                        Integer nBands,
158
                        AffineTransform at,
159
                        Integer outSizeX,
160
                        Integer outSizeY,
161
                        Integer dataType,
162
                        Params params,
163
                        IProjection proj) throws GdalException, IOException {
164
                this(dataWriter, outFileName, nBands, at, outSizeX, outSizeY, dataType, params, proj, new Boolean(true));
165
        }
166
167
        /**
168
         * Constructor para salvar datos servidos por el cliente
169
         * @param dataWriter               Objeto servidor de datos para el driver de escritura
170
         * @param outFilename              Fichero de salida
171
         * @param blockSize                Tama?o de bloque
172
         * @param Extent                   extent
173
         * @param compresion                   Compresi?n si la tiene
174
         * @param outSizeX                          Tama?o de salida en X
175
         * @param outSizeY                        Tama?o de salida en Y
176
         * @param dataType                        Tipo de dato
177
         * @param geo                                Flag que dice si se salva con georreferenciaci?n o sin ella
178
         * @throws GdalException
179
         * @throws IOException
180
         */
181
        public GdalWriter(        IDataWriter dataWriter,
182
                        String outFileName,
183
                        Integer nBands,
184
                        AffineTransform at,
185
                        Integer outSizeX,
186
                        Integer outSizeY,
187
                        Integer dataType,
188
                        Params params,
189
                        IProjection proj,
190
                        Boolean geo)throws GdalException, IOException {
191
192
                this.proj = proj;
193
                ident = outFileName.toLowerCase().substring(outFileName.lastIndexOf(".") + 1);
194
                driver = ((WriteFileFormatFeatures)fileFeature.get(ident)).getDriverName();
195
                this.dataType = dataType.intValue();
196
                this.at = at;
197
                percent = 0;
198
199
                this.dataWriter = dataWriter;
200
                this.outFileName = outFileName;
201
202
                this.sizeWindowX = outSizeX.intValue();
203
                this.sizeWindowY = outSizeY.intValue();
204
205
                if ((sizeWindowX < 0) || (sizeWindowY < 0))
206
                        throw new IOException("Tama?o del fichero de salida erroneo.");
207
208
                this.nBands = nBands.intValue();
209
210
                //Calculamos la georeferenciaci?n a partir del extend pasado por el cliente.
211
212
                geot = new GeoTransform();
213
                geot.adfgeotransform[0] = at.getTranslateX();
214
                geot.adfgeotransform[3] = at.getTranslateY();
215
                geot.adfgeotransform[1] = at.getScaleX();
216
                geot.adfgeotransform[5] = at.getScaleY();
217
                geot.adfgeotransform[2] = at.getShearX();
218
                geot.adfgeotransform[4] = at.getShearY();
219
220
                String outRmf = outFileName.substring(0, outFileName.lastIndexOf("."));
221
                if(geo.booleanValue())
222
                        RasterUtilities.saveGeoInfo(outRmf, at, new Point2D.Double(sizeWindowX, sizeWindowY));
223
224
                if(params == null)
225
                        loadParams(ident);
226
                else
227
                        this.driverParams = params;
228
229
                init();
230
        }
231
232
        /**
233
         * A?ade la proyecci?n Wkt con la que salvar.
234
         * @param wkt
235
         * @throws GdalException
236
         */
237
        public void setWkt(String wkt) {
238
                if(dstDataset != null && wkt != null && wkt.compareTo("unknown") != 0)
239
                        try {
240
                                dstDataset.setProjection(wkt);
241
                        } catch (GdalException e) {
242
                                System.err.println("Proyecci?n Wkt no asignada en GdalWriter");
243
                                return;
244
                        }
245
        }
246
247
        /**
248
         * Asigna el tipo de driver con el que se salvar? la imagen
249
         * @param drvType        Tipo de driver
250
         */
251
        public void setDriverType(String drvType) {
252
                this.driver = drvType;
253
        }
254
255
        /**
256
         * Creaci?n del dataset de destino.
257
         * @throws EcwException
258
         */
259
        private void init() throws GdalException {
260
                //Controlamos que el tipo de driver sea correcto
261
                if (driver == null)
262
                        throw new GdalException("Tipo de driver sin especificar.");
263
264
                boolean okdrvtype = false;
265
266
                String[] types = GeoRasterWriter.getDriversType();
267
                for (int i = 0; i < GeoRasterWriter.getNTypes(); i++)
268
                        if (driver.equals(types[i]))
269
                                okdrvtype = true;
270
271
                if (okdrvtype == false)
272
                        throw new GdalException("El tipo de driver " + driver + " no est? soportado por GdalWriter.");
273
274
                //Obtenemos el driver y creamos el dataset del destino
275
                drv = Gdal.getDriverByName(driver);
276
277
                if (dstDataset != null) {
278
                        dstDataset.close();
279
                        dstDataset = null;
280
                }
281
282
                dstDataset = drv.create(outFileName, sizeWindowX, sizeWindowY,
283
                                nBands, RasterUtilities.getGdalTypeFromRasterBufType(dataType), gdalParamsFromRasterParams(driverParams));
284
285
                dstDataset.setGeoTransform(geot);
286
287
                int blockSize = RasterLibrary.blockHeight;
288
289
                nBlocks = (sizeWindowY / blockSize);
290
                anchoResto = sizeWindowY - (nBlocks * blockSize);
291
        }
292
293
        public void anotherFile(String fileName)throws GdalException {
294
                dstDataset = drv.create(fileName, sizeWindowX, sizeWindowY,
295
                                nBands, RasterUtilities.getGdalTypeFromRasterBufType(dataType), gdalParamsFromRasterParams(driverParams));
296
        }
297
298
        /**
299
         * Convierte los par?metros obtenidos desde el objeto params a parametros
300
         * comprensibles por la librer?a gdal
301
         * @param p Params
302
         * @return Array de par?metros
303
         */
304
        public String[] gdalParamsFromRasterParams(Params p) {
305
                if (p == null)
306
                        return null;
307
                ArrayList paramList = new ArrayList();
308
                Param phot = p.getParamById("photometric");
309
                if (phot != null)
310
                        paramList.add("PHOTOMETRIC=" + phot.list[((Integer) phot.defaultValue).intValue()]);
311
                Param inter = p.getParamById("interleave");
312
                if (inter != null)
313
                        paramList.add("INTERLEAVE=" + inter.list[((Integer) inter.defaultValue).intValue()]);
314
                Param comp = p.getParamById("compression");// GIF LZW, ...
315
                if (comp != null)
316
                        paramList.add("COMPRESS=" + comp.list[((Integer) comp.defaultValue).intValue()]);
317
                Param comp1 = p.getParamById("compress"); // HFA (YES, NO)
318
                if (comp1 != null)
319
                        paramList.add("COMPRESS=" + comp1.list[((Integer) comp1.defaultValue).intValue()]);
320
                Param rrd = p.getParamById("rrd");
321
                if (rrd != null)
322
                        paramList.add("HFA_USE_RRD=" + rrd.list[((Integer) rrd.defaultValue).intValue()]);
323
                Param mtw = p.getParamById("Mtw");
324
                if (mtw != null)
325
                        paramList.add("MTW=" + mtw.list[((Integer) mtw.defaultValue).intValue()]);
326
                Param tw = p.getParamById("Tile Width");
327
                if (tw != null)
328
                        paramList.add("BLOCKXSIZE=" + tw.list[((Integer) tw.defaultValue).intValue()]);
329
                Param th = p.getParamById("Tile Height");
330
                if (th != null)
331
                        paramList.add("BLOCKYSIZE=" + th.list[((Integer) th.defaultValue).intValue()]);
332
                Param qt = p.getParamById("quality");
333
                if (qt != null)
334
                        paramList.add("QUALITY=" + qt.defaultValue);
335
                Param prog = p.getParamById("progressive");
336
                if (prog != null)
337
                        paramList.add("PROGRESSIVE=" + prog.defaultValue);
338
339
                if (paramList.size() == 0)
340
                        return null;
341
342
                String[] result = new String[paramList.size()];
343
                for (int i = 0; i < result.length; i++)
344
                        result[i] = (String) paramList.get(i);
345
                return result;
346
        }
347
348
        /**
349
         * Escritura de datos tipo Byte.
350
         * @param sizeY Alto del bloque que se escribe.
351
         * @param posicionY Posici?ny a partir desde donde se comienza.
352
         */
353
        public void writeByteBand(int sizeY, int posicionY) {
354
                byte[][] buftmp = dataWriter.readByteData(sizeWindowX, sizeY);
355
                for(int iBand = 0; iBand < nBands; iBand ++)
356
                        bufBands[iBand].buffByte = new byte[buftmp[iBand].length];
357
358
                //Escribimos el bloque destino
359
                for (int iBand = 0; iBand < buftmp.length; iBand++)
360
                        for (int i = 0; i < buftmp[iBand].length; i++)
361
                                bufBands[iBand].buffByte[i] = buftmp[iBand][i];
362
363
                for (int iBand = 0; iBand < buftmp.length; iBand++)
364
                        try {
365
                                rband = dstDataset.getRasterBand(iBand + 1);
366
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Byte);
367
                        } catch (GdalException e) {
368
                                //No se est? escribiendo ...
369
                        }
370
        }
371
372
        /**
373
         * Escritura de datos tipo Short.
374
         * @param sizeY Alto del bloque que se escribe.
375
         * @param posicionY Posici?ny a partir desde donde se comienza.
376
         */
377
        public void writeShortBand(int sizeY, int posicionY) {
378
                short[][] buftmp = dataWriter.readShortData(sizeWindowX, sizeY);
379
                for(int iBand = 0; iBand < nBands; iBand ++)
380
                        bufBands[iBand].buffShort = new short[buftmp[iBand].length];
381
382
                //Escribimos el bloque destino
383
                for (int iBand = 0; iBand < nBands; iBand++)
384
                        for (int i = 0; i < buftmp[iBand].length; i++)
385
                                bufBands[iBand].buffShort[i] = buftmp[iBand][i];
386
387
                for (int iBand = 0; iBand < nBands; iBand++)
388
                        try {
389
                                rband = dstDataset.getRasterBand(iBand + 1);
390
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Int16);
391
                        } catch (GdalException e) {
392
                                //No se est? escribiendo ...
393
                        }
394
        }
395
396
        /**
397
         * Escritura de datos tipo Int.
398
         * @param sizeY Alto del bloque que se escribe.
399
         * @param posicionY Posici?ny a partir desde donde se comienza.
400
         */
401
        public void writeIntBand(int sizeY, int posicionY) {
402
                int[][] buftmp = dataWriter.readIntData(sizeWindowX, sizeY);
403
                for(int iBand = 0; iBand < nBands; iBand ++)
404
                        bufBands[iBand].buffInt = new int[buftmp[iBand].length];
405
406
                //Escribimos el bloque destino
407
                for (int iBand = 0; iBand < buftmp.length; iBand++)
408
                        for (int i = 0; i < buftmp[iBand].length; i++)
409
                                bufBands[iBand].buffInt[i] = buftmp[iBand][i];
410
411
                for (int iBand = 0; iBand < buftmp.length; iBand++)
412
                        try {
413
                                rband = dstDataset.getRasterBand(iBand + 1);
414
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Int32);
415
                        } catch (GdalException e) {
416
                                //No se est? escribiendo ...
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
         * Escritura de datos tipo Double.
446
         * @param sizeY Alto del bloque que se escribe.
447
         * @param posicionY Posici?ny a partir desde donde se comienza.
448
         */
449
        public void writeDoubleBand(int sizeY, int posicionY) {
450
                double[][] buftmp = dataWriter.readDoubleData(sizeWindowX, sizeY);
451
                for(int iBand = 0; iBand < nBands; iBand ++)
452
                        bufBands[iBand].buffDouble = new double[buftmp[iBand].length];
453
454
                //Escribimos el bloque destino
455
                for (int iBand = 0; iBand < buftmp.length; iBand++)
456
                        for (int i = 0; i < buftmp[iBand].length; i++)
457
                                bufBands[iBand].buffDouble[i] = buftmp[iBand][i];
458
459
                for (int iBand = 0; iBand < buftmp.length; iBand++)
460
                        try {
461
                                rband = dstDataset.getRasterBand(iBand + 1);
462
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Float64);
463
                        } catch (GdalException e) {
464
                                //No se est? escribiendo ...
465
                        }
466
        }
467
        /**
468
         * Escritura para tipo de dato ARGB.
469
         * @param sizeY Alto del bloque que se escribe.
470
         * @param posicionY Posici?ny a partir desde donde se comienza.
471
         */
472
        public void writeARGBBand(int sizeY, int posicionY)
473
                        throws InterruptedException, OutOfMemoryError {
474
                int[] buftmp = dataWriter.readARGBData(sizeWindowX, sizeY, 0);
475
                for(int iBand = 0; iBand < nBands; iBand ++)
476
                        bufBands[iBand].buffByte = new byte[buftmp.length];
477
478
                //Escribimos el bloque destino
479
                for (int i = 0; i < buftmp.length; i++) {
480
                        bufBands[0].buffByte[i] = (byte) (((buftmp[i] & 0xff0000) >> 16) &
481
                                        0xff);
482
                        bufBands[1].buffByte[i] = (byte) (((buftmp[i] & 0xff00) >> 8) & 0xff);
483
                        bufBands[2].buffByte[i] = (byte) ((buftmp[i] & 0xff) & 0xff);
484
                }
485
486
                try {
487
                        rband = dstDataset.getRasterBand(1);
488
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[0],
489
                                        Gdal.GDT_Byte);
490
                        rband = dstDataset.getRasterBand(2);
491
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[1],
492
                                        Gdal.GDT_Byte);
493
                        rband = dstDataset.getRasterBand(3);
494
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[2],
495
                                        Gdal.GDT_Byte);
496
                } catch (GdalException e) {
497
                        e.printStackTrace();
498
                }
499
        }
500
501
        /**
502
         * Escribe tres bandas en el GDALRasterBand desde el IDataWriter con una
503
         * altura definida por sizeY.
504
         * @param buftmp        Buffer
505
         * @param sizeY        Altura en pixels del bloque leido
506
         * @param posicionY        Posici?n y a partir de la cual se escribe en el GDALRasterBand destino
507
         */
508
        private void writeBands(int sizeY, int posicionY)
509
                        throws InterruptedException, OutOfMemoryError {
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
                        OutOfMemoryError {
542
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
543
544
                bufBands = new GdalBuffer[nBands];
545
                for(int iBand = 0; iBand < nBands; iBand ++)
546
                        bufBands[iBand] = new GdalBuffer();
547
548
                int blockSize = RasterLibrary.blockHeight;
549
550
                percent = 0;
551
                nBlocks = (sizeWindowY / blockSize);
552
                int increment = (blockSize * 100) / sizeWindowY;
553
554
                if (mode == GeoRasterWriter.MODE_DATAWRITE)
555
                        for (int iBlock = 0; iBlock < nBlocks; iBlock++) {
556
                                if(task.getEvent() != null)
557
                                        task.manageEvent(task.getEvent());
558
                                int posicionY = iBlock * blockSize;
559
                                if(write)
560
                                        writeBands( blockSize, posicionY);
561
                                percent = (iBlock + 1) * increment;
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
         * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
578
         * @throws IOException
579
         */
580
        public void fileWrite() throws IOException, InterruptedException {
581
                write(GeoRasterWriter.MODE_FILEWRITE);
582
        }
583
584
        /**
585
         * Realiza una copia en el formato especificado.
586
         * @throws IOException
587
         */
588
        public static void createCopy(es.gva.cit.jgdal.GdalDriver driverDst, String dst, String src,
589
                        boolean bstrict, String[] params, IProjection proj) throws IOException, GdalException {
590
                if (dst == null || src == null)
591
                        throw new IOException("No se ha asignado un fichero de entrada.");
592
593
                GdalDriver gdalFile;
594
                try {
595
                        gdalFile = new GdalDriver(proj, src);
596
                        Gdal dstDataset = driverDst.createCopy(dst, gdalFile.getNative(), bstrict, params);
597
                        if(        dst.endsWith(".jpg") ||
598
                                dst.endsWith(".jpeg") ||
599
                                dst.endsWith(".png"))
600
                                RasterUtilities.createWorldFile(dst, gdalFile.getExtent(), gdalFile.getWidth(), gdalFile.getHeight());
601
                        gdalFile.close();
602
                        dstDataset.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
         * @throws RmfSerializerException
612
         */
613
        public void dataWrite() throws IOException, InterruptedException,
614
                        OutOfMemoryError {
615
                if (dataWriter == null)
616
                        throw new IOException("No se ha obtenido un objeto de entrada para la escritura valido.");
617
618
                write(GeoRasterWriter.MODE_DATAWRITE);
619
620
                if (driverParams.getParamById("tfw") != null &&
621
                                driverParams.getParamById("tfw").defaultValue instanceof Boolean &&
622
                                ((Boolean) driverParams.getParamById("tfw").defaultValue).booleanValue() == true)
623
                        if (at != null)
624
                                RasterUtilities.createWorldFile(this.outFileName, at, sizeWindowX, sizeWindowY);
625
626
                if (colorInterp != null)
627
                        try {
628
                                RasterDataset.saveObjectToRmfFile(outFileName, DatasetColorInterpretation.class, colorInterp);
629
                        } catch (RmfSerializerException e) {
630
                                throw new IOException("No se ha podido guardar la interpretacion de color");
631
                        }
632
        }
633
634
        /**
635
         * Cancela el salvado de datos.
636
         * @throws GdalException
637
         */
638
        public void writeClose() {
639
                try {
640
                        if(dstDataset != null)
641
                                dstDataset.close();
642
                } catch (GdalException e) {
643
                        e.printStackTrace();
644
                }
645
        }
646
647
        /**
648
         * Cancela el salvado de datos.
649
         */
650
        public void writeCancel() {
651
                write = false;
652
        }
653
654
        /**
655
         * Obtiene el valor a la variable write que estar? a true cuando se est? escribiendo
656
         *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
657
         * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
658
         * de salida.
659
         * @return True si puede escribirse y false si no puede
660
         */
661
        public boolean isWrite() {
662
                return write;
663
        }
664
665
        /**
666
         * Asigna el valor a la variable write que estar? a true cuando se est? escribiendo
667
         *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
668
         * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
669
         * de salida.
670
         * @param write Variable booleana. True si puede escribirse y false si no puede
671
         */
672
        public void setWrite(boolean write) {
673
                this.write = write;
674
        }
675
676
        /**
677
         * Asigna los par?metros del driver modificados por el cliente.
678
         * @param Params
679
         */
680
        public void setParams(Params params) {
681
                this.driverParams = params;
682
683
                int blockSize = 256;
684
                try {
685
                        Param param = driverParams.getParamById("blocksize");
686
                        blockSize = Integer.parseInt(param.list[((Integer)param.defaultValue).intValue()]);
687
                        nBlocks = (sizeWindowY / blockSize);
688
                        anchoResto = sizeWindowY - (nBlocks * blockSize);
689
                }catch(NumberFormatException e) {
690
                        //Se queda con el valor de inicializaci?n
691
                }
692
        }
693
}