Statistics
| Revision:

gvsig-raster / org.gvsig.raster.gdal / trunk / org.gvsig.raster.gdal / org.gvsig.raster.gdal.io / src / main / java / org / gvsig / raster / gdal / io / GdalWriter.java @ 1073

History | View | Annotate | Download (26 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.gdal.io;
23

    
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.Point2D;
26
import java.io.File;
27
import java.io.IOException;
28
import java.util.ArrayList;
29

    
30
import org.cresques.cts.IProjection;
31
import org.gvsig.fmap.dal.coverage.RasterLibrary;
32
import org.gvsig.fmap.dal.coverage.RasterLocator;
33
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
34
import org.gvsig.fmap.dal.coverage.datastruct.Params;
35
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
36
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
37
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
38
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
39
import org.gvsig.jgdal.Gdal;
40
import org.gvsig.jgdal.GdalBuffer;
41
import org.gvsig.jgdal.GdalDriver;
42
import org.gvsig.jgdal.GdalException;
43
import org.gvsig.jgdal.GdalRasterBand;
44
import org.gvsig.jgdal.GeoTransform;
45
import org.gvsig.raster.gdal.io.features.BMPFeatures;
46
import org.gvsig.raster.gdal.io.features.GTiffFeatures;
47
import org.gvsig.raster.gdal.io.features.HFAFeatures;
48
import org.gvsig.raster.gdal.io.features.IDRISIFeatures;
49
import org.gvsig.raster.gdal.io.features.ILWIS_MprFeatures;
50
import org.gvsig.raster.gdal.io.features.PNM_PgmFeatures;
51
import org.gvsig.raster.gdal.io.features.PNM_PpmFeatures;
52
import org.gvsig.raster.impl.buffer.DefaultDataServerWriter;
53
import org.gvsig.raster.impl.buffer.RasterBuffer;
54
import org.gvsig.raster.impl.process.RasterTask;
55
import org.gvsig.raster.impl.process.RasterTaskQueue;
56
import org.gvsig.raster.impl.store.ParamImpl;
57
import org.gvsig.raster.impl.store.ParamsImpl;
58
import org.gvsig.raster.impl.store.WriteFileFormatFeatures;
59
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
60
import org.gvsig.raster.impl.store.writer.DefaultRasterWriter;
61
import org.gvsig.raster.util.DefaultProviderServices;
62
import org.gvsig.tools.ToolsLocator;
63
import org.gvsig.tools.extensionpoint.ExtensionPoint;
64
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
65

    
66

    
67
/**
68
 * Driver para la escritura a trav?s de Gdal.
69
 * Puede exportar un fichero de un formato a otro desde un GeoRasterFile
70
 * en cualquier formato soportado por la lectura a un formato que este incluido
71
 * en la lista supportedDrv.
72
 *
73
 * Puede salvar a disco en un formato que este incluido en la lista supportedDrv
74
 * obteniendo los datos que van siendo servidos desde el cliente. Este cliente
75
 * debe implementar un DataServerWriter o tener un objeto que lo implemente. Inicialmente
76
 * le pasar? los par?metros de la imagen de salida y cuando el driver comience a
77
 * escribir le ir? solicitando m?s a trav?s del m?todo readData de DataServerWriter.
78
 * El cliente ser? el que lleve el control de lo que va sirviendo y lo que le queda
79
 * por servir.
80
 * @author Nacho Brodin (nachobrodin@gmail.com)
81
 */
82
public class GdalWriter extends DefaultRasterWriter {
83

    
84
        public static void register() {
85
                DefaultProviderServices pInfo = (DefaultProviderServices)RasterLocator.getManager().getProviderServices();
86
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
87
                ExtensionPoint point = extensionPoints.get("RasterWriter");
88

    
89
                point.append("tif", "", GdalWriter.class);
90
                pInfo.getFileFeature().put("tif", new GTiffFeatures());
91

    
92
                point.append("img", "", GdalWriter.class);
93
                pInfo.getFileFeature().put("img", new HFAFeatures());
94

    
95
                point.append("bmp", "", GdalWriter.class);
96
                pInfo.getFileFeature().put("bmp", new BMPFeatures());
97

    
98
                point.append("pgm", "", GdalWriter.class);
99
                pInfo.getFileFeature().put("pgm", new PNM_PgmFeatures());
100

    
101
                point.append("ppm", "", GdalWriter.class);
102
                pInfo.getFileFeature().put("ppm", new PNM_PpmFeatures());
103

    
104
                point.append("mpl", "", GdalWriter.class);
105
                pInfo.getFileFeature().put("mpl", new ILWIS_MprFeatures());
106

    
107
                point.append("rst", "", GdalWriter.class);
108
                pInfo.getFileFeature().put("rst", new IDRISIFeatures());
109

    
110
                //La exportaci?n no es correcta del todo
111
                //point.register("rmf", GdalWriter.class);
112
                //fileFeature.put("rmf", new RMFFeatures());
113

    
114
                //No salva datos. Siempre sale negra la imagen
115
                //point.register("aux", GdalWriter.class);
116
                //fileFeature.put("aux", new PAuxFeatures());
117
        }
118

    
119
        private GdalDriver                                 drv;
120
        private Gdal                                                         dstDataset = null;
121
        private GdalRasterBand                                         rband = null;
122
        private GeoTransform                                         geot = null; //Datos de georeferenciaci?n
123
        //private OGRSpatialReference                         oSRS; //Datos de proyecci?n
124
        private GdalBuffer[]                                        bufBands = null;
125
        private int                                                         nBlocks = 0; //N?mero de bloques en Y en el que se divide la imagen para escribir
126
        private int                                                         anchoResto = 0; //Tama?o del ?ltimo bloque de la imagen.
127
        private boolean                                                        write = true; //Cuando est? a true se puede escribir en la imagen de salida. Si est? a false el proceso es interrumpido
128
        private int                                                         dataType = RasterBuffer.TYPE_UNDEFINED;
129

    
130
        /**
131
         * Carga los par?metros de este driver.
132
         */
133
        public void loadParams(String ident) {
134
                WriteFileFormatFeatures wfff = (WriteFileFormatFeatures)pInfo.getFileFeature().get(ident);
135
                wfff.loadParams();
136
                driverParams = (ParamsImpl)wfff.getParams();
137
        }
138
        
139
        /*
140
         * (non-Javadoc)
141
         * @see org.gvsig.fmap.dal.coverage.store.RasterWriter#getProviderName()
142
         */
143
        public String getProviderName() {
144
                return GdalProvider.NAME;
145
        }
146

    
147
        /**
148
         * Constructor para la obtenci?n de par?metros del driver
149
         * @param drvType        Tipo de driver
150
         */
151
        public GdalWriter(String fileName) {
152
                ident = fileUtil.getExtensionFromFileName(fileName);
153
                driver = ((WriteFileFormatFeatures)pInfo.getFileFeature().get(ident)).getDriverName();
154

    
155
                loadParams(ident);
156
        }
157

    
158
        /**
159
         * Constructor para salvar datos servidos por el cliente
160
         * @param dataWriter               Objeto servidor de datos para el driver de escritura
161
         * @param outFilename              Fichero de salida
162
         * @param blockSize                Tama?o de bloque
163
         * @param Extent                   extent
164
         * @param compresion                   Compresi?n si la tiene
165
         * @param outSizeX                          Tama?o de salida en X
166
         * @param outSizeY                        Tama?o de salida en Y
167
         * @param dataType                        Tipo de dato
168
         * @throws GdalException
169
         * @throws IOException
170
         */
171
        public GdalWriter(        DataServerWriter dataWriter,
172
                        String outFileName,
173
                        Integer nBands,
174
                        AffineTransform at,
175
                        Integer outSizeX,
176
                        Integer outSizeY,
177
                        Integer dataType,
178
                        Params params,
179
                        IProjection proj) throws GdalException, IOException {
180
                this(dataWriter, outFileName, nBands, at, outSizeX, outSizeY, dataType, params, proj, new Boolean(true));
181
        }
182

    
183
        /**
184
         * Constructor para salvar datos servidos por el cliente
185
         * @param dataWriter               Objeto servidor de datos para el driver de escritura
186
         * @param outFilename              Fichero de salida
187
         * @param blockSize                Tama?o de bloque
188
         * @param Extent                   extent
189
         * @param compresion                   Compresi?n si la tiene
190
         * @param outSizeX                          Tama?o de salida en X
191
         * @param outSizeY                        Tama?o de salida en Y
192
         * @param dataType                        Tipo de dato
193
         * @param geo                                Flag que dice si se salva con georreferenciaci?n o sin ella
194
         * @throws GdalException
195
         * @throws IOException
196
         */
197
        public GdalWriter(        DataServerWriter dataWriter,
198
                        String outFileName,
199
                        Integer nBands,
200
                        AffineTransform at,
201
                        Integer outSizeX,
202
                        Integer outSizeY,
203
                        Integer dataType,
204
                        Params params,
205
                        IProjection proj,
206
                        Boolean geo)throws GdalException, IOException {
207

    
208
                this.proj = proj;
209
                ident = outFileName.toLowerCase().substring(outFileName.lastIndexOf(".") + 1);
210
                driver = ((WriteFileFormatFeatures)pInfo.getFileFeature().get(ident)).getDriverName();
211
                this.dataType = dataType.intValue();
212
                this.at = at;
213
                percent = 0;
214

    
215
                this.dataWriter = dataWriter;
216
                this.outFileName = outFileName;
217

    
218
                this.sizeWindowX = outSizeX.intValue();
219
                this.sizeWindowY = outSizeY.intValue();
220

    
221
                if ((sizeWindowX < 0) || (sizeWindowY < 0))
222
                        throw new IOException("Tama?o del fichero de salida erroneo.");
223

    
224
                this.nBands = nBands.intValue();
225

    
226
                //Calculamos la georeferenciaci?n a partir del extend pasado por el cliente.
227

    
228
                geot = new GeoTransform();
229
                geot.adfgeotransform[0] = at.getTranslateX();
230
                geot.adfgeotransform[3] = at.getTranslateY();
231
                geot.adfgeotransform[1] = at.getScaleX();
232
                geot.adfgeotransform[5] = at.getScaleY();
233
                geot.adfgeotransform[2] = at.getShearX();
234
                geot.adfgeotransform[4] = at.getShearY();
235

    
236
                String outRmf = outFileName.substring(0, outFileName.lastIndexOf("."));
237
                if(geo.booleanValue())
238
                        rasterUtil.saveGeoInfo(outRmf, at, new Point2D.Double(sizeWindowX, sizeWindowY));
239

    
240
                if(params == null)
241
                        loadParams(ident);
242
                else
243
                        if(params instanceof ParamsImpl)
244
                                this.driverParams = (ParamsImpl)params;
245

    
246
                init();
247
        }
248

    
249
        /**
250
         * A?ade la proyecci?n Wkt con la que salvar.
251
         * @param wkt
252
         * @throws GdalException
253
         */
254
        public void setWkt(String wkt) {
255
                if(dstDataset != null && wkt != null && wkt.compareTo("unknown") != 0)
256
                        try {
257
                                dstDataset.setProjection(wkt);
258
                        } catch (GdalException e) {
259
                                System.err.println("Proyecci?n Wkt no asignada en GdalWriter");
260
                                return;
261
                        }
262
        }
263

    
264
        /**
265
         * Asigna el tipo de driver con el que se salvar? la imagen
266
         * @param drvType        Tipo de driver
267
         */
268
        public void setDriverType(String drvType) {
269
                this.driver = drvType;
270
        }
271

    
272
        /**
273
         * Creaci?n del dataset de destino.
274
         * @throws EcwException
275
         */
276
        private void init() throws GdalException {
277
                //Controlamos que el tipo de driver sea correcto
278
                if (driver == null)
279
                        throw new GdalException("Tipo de driver sin especificar.");
280

    
281
                boolean okdrvtype = false;
282

    
283
                String[] types = pInfo.getWriteDriversType();
284
                for (int i = 0; i < pInfo.getWriteNTypes(); i++)
285
                        if (driver.equals(types[i]))
286
                                okdrvtype = true;
287

    
288
                if (okdrvtype == false)
289
                        throw new GdalException("El tipo de driver " + driver + " no est? soportado por GdalWriter.");
290

    
291
                //Obtenemos el driver y creamos el dataset del destino
292
                drv = Gdal.getDriverByName(driver);
293

    
294
                if (dstDataset != null) {
295
                        dstDataset.close();
296
                        dstDataset = null;
297
                }
298

    
299
                dstDataset = drv.create(outFileName, sizeWindowX, sizeWindowY,
300
                                nBands, rasterUtil.getGdalTypeFromRasterBufType(dataType), gdalParamsFromRasterParams(driverParams));
301

    
302
                dstDataset.setGeoTransform(geot);
303

    
304
                int blockSize = RasterLibrary.blockHeight;
305

    
306
                nBlocks = (sizeWindowY / blockSize);
307
                anchoResto = sizeWindowY - (nBlocks * blockSize);
308
        }
309

    
310
        public void anotherFile(String fileName)throws GdalException {
311
                dstDataset = drv.create(fileName, sizeWindowX, sizeWindowY,
312
                                nBands, rasterUtil.getGdalTypeFromRasterBufType(dataType), gdalParamsFromRasterParams(driverParams));
313
        }
314

    
315
        /**
316
         * Convierte los par?metros obtenidos desde el objeto params a parametros
317
         * comprensibles por la librer?a gdal
318
         * @param p Params
319
         * @return Array de par?metros
320
         */
321
        public String[] gdalParamsFromRasterParams(Params p) {
322
                if (p == null)
323
                        return null;
324
                ArrayList<String> paramList = new ArrayList<String>();
325
                ParamImpl phot = (ParamImpl)p.getParamById("photometric");
326
                if (phot != null)
327
                        paramList.add("PHOTOMETRIC=" + phot.getList()[((Integer) phot.getDefaultValue()).intValue()]);
328
                ParamImpl inter = (ParamImpl)p.getParamById("interleave");
329
                if (inter != null)
330
                        paramList.add("INTERLEAVE=" + inter.getList()[((Integer) inter.getDefaultValue()).intValue()]);
331
                ParamImpl comp = (ParamImpl)p.getParamById("compression");// GIF LZW, ...
332
                if (comp != null)
333
                        paramList.add("COMPRESS=" + comp.getList()[((Integer) comp.getDefaultValue()).intValue()]);
334
                ParamImpl comp1 = (ParamImpl)p.getParamById("compress"); // HFA (YES, NO)
335
                if (comp1 != null)
336
                        paramList.add("COMPRESS=" + comp1.getList()[((Integer) comp1.getDefaultValue()).intValue()]);
337
                ParamImpl rrd = (ParamImpl)p.getParamById("rrd");
338
                if (rrd != null)
339
                        paramList.add("HFA_USE_RRD=" + rrd.getList()[((Integer) rrd.getDefaultValue()).intValue()]);
340
                ParamImpl mtw = (ParamImpl)p.getParamById("Mtw");
341
                if (mtw != null)
342
                        paramList.add("MTW=" + mtw.getList()[((Integer) mtw.getDefaultValue()).intValue()]);
343
                ParamImpl tw = (ParamImpl)p.getParamById("Tile Width");
344
                if (tw != null)
345
                        paramList.add("BLOCKXSIZE=" + tw.getList()[((Integer) tw.getDefaultValue()).intValue()]);
346
                ParamImpl th = (ParamImpl)p.getParamById("Tile Height");
347
                if (th != null)
348
                        paramList.add("BLOCKYSIZE=" + th.getList()[((Integer) th.getDefaultValue()).intValue()]);
349
                ParamImpl qt = (ParamImpl)p.getParamById("quality");
350
                if (qt != null)
351
                        paramList.add("QUALITY=" + qt.getDefaultValue());
352
                ParamImpl prog = (ParamImpl)p.getParamById("progressive");
353
                if (prog != null)
354
                        paramList.add("PROGRESSIVE=" + prog.getDefaultValue());
355

    
356
                if (paramList.size() == 0)
357
                        return null;
358

    
359
                String[] result = new String[paramList.size()];
360
                for (int i = 0; i < result.length; i++)
361
                        result[i] = (String) paramList.get(i);
362
                return result;
363
        }
364

    
365
        /**
366
         * Escritura de datos tipo Byte.
367
         * @param sizeY Alto del bloque que se escribe.
368
         * @param posicionY Posici?ny a partir desde donde se comienza.
369
         */
370
        public void writeByteBand(int sizeY, int posicionY) {
371
                byte[][] buftmp = dataWriter.readByteData(sizeWindowX, sizeY);
372
                for(int iBand = 0; iBand < nBands; iBand ++)
373
                        bufBands[iBand].buffByte = new byte[buftmp[iBand].length];
374

    
375
                //Escribimos el bloque destino
376
                for (int iBand = 0; iBand < buftmp.length; iBand++)
377
                        for (int i = 0; i < buftmp[iBand].length; i++)
378
                                bufBands[iBand].buffByte[i] = buftmp[iBand][i];
379

    
380
                for (int iBand = 0; iBand < buftmp.length; iBand++)
381
                        try {
382
                                rband = dstDataset.getRasterBand(iBand + 1);
383
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Byte);
384
                                bufBands[iBand].buffByte = null;
385
                        } catch (GdalException e) {
386
                                //No se est? escribiendo ...
387
                        }
388
                buftmp = null;
389
                
390
        }
391

    
392
        /**
393
         * Escritura de datos tipo Short.
394
         * @param sizeY Alto del bloque que se escribe.
395
         * @param posicionY Posici?ny a partir desde donde se comienza.
396
         */
397
        public void writeShortBand(int sizeY, int posicionY) {
398
                short[][] buftmp = dataWriter.readShortData(sizeWindowX, sizeY);
399
                for(int iBand = 0; iBand < nBands; iBand ++)
400
                        bufBands[iBand].buffShort = new short[buftmp[iBand].length];
401

    
402
                //Escribimos el bloque destino
403
                for (int iBand = 0; iBand < nBands; iBand++)
404
                        for (int i = 0; i < buftmp[iBand].length; i++)
405
                                bufBands[iBand].buffShort[i] = buftmp[iBand][i];
406

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

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

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

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

    
444
        /**
445
         * Escritura de datos tipo Float.
446
         * @param sizeY Alto del bloque que se escribe.
447
         * @param posicionY Posici?ny a partir desde donde se comienza.
448
         */
449
        public void writeFloatBand(int sizeY, int posicionY) {
450
                float[][] buftmp = dataWriter.readFloatData(sizeWindowX, sizeY);
451
                for(int iBand = 0; iBand < nBands; iBand ++)
452
                        bufBands[iBand].buffFloat = new float[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].buffFloat[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_Float32);
463
                                bufBands[iBand].buffFloat = null;
464
                        } catch (GdalException e) {
465
                                //No se est? escribiendo ...
466
                        }
467
                buftmp = null;
468
        }
469

    
470
        /**
471
         * Escritura de datos tipo Double.
472
         * @param sizeY Alto del bloque que se escribe.
473
         * @param posicionY Posici?ny a partir desde donde se comienza.
474
         */
475
        public void writeDoubleBand(int sizeY, int posicionY) {
476
                double[][] buftmp = dataWriter.readDoubleData(sizeWindowX, sizeY);
477
                for(int iBand = 0; iBand < nBands; iBand ++)
478
                        bufBands[iBand].buffDouble = new double[buftmp[iBand].length];
479

    
480
                //Escribimos el bloque destino
481
                for (int iBand = 0; iBand < buftmp.length; iBand++)
482
                        for (int i = 0; i < buftmp[iBand].length; i++)
483
                                bufBands[iBand].buffDouble[i] = buftmp[iBand][i];
484

    
485
                for (int iBand = 0; iBand < buftmp.length; iBand++)
486
                        try {
487
                                rband = dstDataset.getRasterBand(iBand + 1);
488
                                rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[iBand], Gdal.GDT_Float64);
489
                                bufBands[iBand].buffDouble = null;
490
                        } catch (GdalException e) {
491
                                //No se est? escribiendo ...
492
                        }
493
                buftmp = null;
494
        }
495
        /**
496
         * Escritura para tipo de dato ARGB.
497
         * @param sizeY Alto del bloque que se escribe.
498
         * @param posicionY Posici?ny a partir desde donde se comienza.
499
         */
500
        public void writeARGBBand(int sizeY, int posicionY)
501
                        throws ProcessInterruptedException, OutOfMemoryError {
502
                int[] buftmp = dataWriter.readARGBData(sizeWindowX, sizeY, 0);
503
                for(int iBand = 0; iBand < nBands; iBand ++)
504
                        bufBands[iBand].buffByte = new byte[buftmp.length];
505

    
506
                //Escribimos el bloque destino
507
                for (int i = 0; i < buftmp.length; i++) {
508
                        bufBands[0].buffByte[i] = (byte) (((buftmp[i] & 0xff0000) >> 16) &
509
                                        0xff);
510
                        bufBands[1].buffByte[i] = (byte) (((buftmp[i] & 0xff00) >> 8) & 0xff);
511
                        bufBands[2].buffByte[i] = (byte) ((buftmp[i] & 0xff) & 0xff);
512
                }
513

    
514
                try {
515
                        rband = dstDataset.getRasterBand(1);
516
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[0],
517
                                        Gdal.GDT_Byte);
518
                        rband = dstDataset.getRasterBand(2);
519
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[1],
520
                                        Gdal.GDT_Byte);
521
                        rband = dstDataset.getRasterBand(3);
522
                        rband.writeRaster(0, posicionY, sizeWindowX, sizeY, bufBands[2],
523
                                        Gdal.GDT_Byte);
524
                } catch (GdalException e) {
525
                        e.printStackTrace();
526
                }
527
                
528
                bufBands[0].buffByte = null;
529
                bufBands[1].buffByte = null;
530
                bufBands[2].buffByte = null;
531
        }
532

    
533
        /**
534
         * Escribe tres bandas en el GDALRasterBand desde el DataServerWriter con una
535
         * altura definida por sizeY.
536
         * @param buftmp        Buffer
537
         * @param sizeY        Altura en pixels del bloque leido
538
         * @param posicionY        Posici?n y a partir de la cual se escribe en el GDALRasterBand destino
539
         */
540
        private void writeBands(int sizeY, int posicionY)
541
                        throws ProcessInterruptedException, OutOfMemoryError {
542
                //leemos el bloque origen
543

    
544
                switch(dataType){
545
                case RasterBuffer.TYPE_IMAGE:
546
                        writeARGBBand(sizeY, posicionY);
547
                        break;
548
                case RasterBuffer.TYPE_BYTE:
549
                        writeByteBand(sizeY, posicionY);
550
                        break;
551
                case RasterBuffer.TYPE_SHORT:
552
                        writeShortBand(sizeY, posicionY);
553
                        break;
554
                case RasterBuffer.TYPE_INT:
555
                        writeIntBand(sizeY, posicionY);
556
                        break;
557
                case RasterBuffer.TYPE_FLOAT:
558
                        writeFloatBand(sizeY, posicionY);
559
                        break;
560
                case RasterBuffer.TYPE_DOUBLE:
561
                        writeDoubleBand(sizeY, posicionY);
562
                        break;
563
                }
564
        }
565

    
566
        /**
567
         * Funci?n que gestiona la lectura desde el origen y la escritura
568
         * de Gdal sobre el fichero destino.
569
         * @param mode        Modo de escritura
570
         * @throws IOException
571
         */
572
        private void write(int mode) throws IOException, ProcessInterruptedException,
573
                        OutOfMemoryError {
574
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
575

    
576
                bufBands = new GdalBuffer[nBands];
577
                for(int iBand = 0; iBand < nBands; iBand ++)
578
                        bufBands[iBand] = new GdalBuffer();
579

    
580
                int blockSize = RasterLibrary.blockHeight;
581
                if(dataWriter instanceof DefaultDataServerWriter) {
582
                        Buffer source = ((DefaultDataServerWriter)dataWriter).getSource();
583
                        if(source.isCached()) {
584
                                blockSize = source.getBlockHeight();
585
                        }
586
                }
587

    
588
                percent = 0;
589
                nBlocks = (sizeWindowY / blockSize);
590
                int increment = (blockSize * 100) / sizeWindowY;
591

    
592
                if (mode == DefaultRasterWriter.MODE_DATAWRITE)
593
                        for (int iBlock = 0; iBlock < nBlocks; iBlock++) {
594
                                if(task.getEvent() != null)
595
                                        task.manageEvent(task.getEvent());
596
                                int posicionY = iBlock * blockSize;
597
                                if(write)
598
                                        writeBands( blockSize, posicionY);
599
                                percent = (iBlock + 1) * increment;
600
                        }
601

    
602
                if (anchoResto != 0)
603
                        if (mode == DefaultRasterWriter.MODE_DATAWRITE) {
604
                                if(task.getEvent() != null)
605
                                        task.manageEvent(task.getEvent());
606
                                int posicionY = nBlocks * blockSize;
607
                                if(write)
608
                                        writeBands(anchoResto, posicionY);
609
                                percent = nBlocks * increment;
610
                        }
611

    
612
        }
613

    
614
        /**
615
         * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
616
         * @throws IOException
617
         */
618
        public void fileWrite() throws IOException, ProcessInterruptedException {
619
                write(DefaultRasterWriter.MODE_FILEWRITE);
620
        }
621

    
622
        /**
623
         * Realiza una copia en el formato especificado.
624
         * @throws IOException
625
         */
626
        public static void createCopy(GdalDriver driverDst, String dst, String src,
627
                        boolean bstrict, String[] params) throws IOException, GdalException {
628
                if (dst == null || src == null)
629
                        throw new IOException("No se ha asignado un fichero de entrada.");
630

    
631
                GdalProvider gdalFile;
632
                try {
633
                        GdalDataParameters par = new GdalDataParameters();
634
                        par.setFile(new File(src));
635
                        gdalFile = new GdalProvider(par, null);
636
                        Gdal dstDataset = driverDst.createCopy(dst, gdalFile.getNative(), bstrict, params);
637
                        if(        dst.endsWith(".jpg") ||
638
                                dst.endsWith(".jpeg") ||
639
                                dst.endsWith(".png"))
640
                                RasterLocator.getManager().getFileUtils().createWorldFile(dst, gdalFile.getExtent(), (int)gdalFile.getWidth(), (int)gdalFile.getHeight());
641
                        gdalFile.close();
642
                        dstDataset.close();
643
                } catch (NotSupportedExtensionException e) {
644
                        e.printStackTrace();
645
                }
646
        }
647

    
648
        /**
649
         * Realiza la escritura de datos con los datos que le pasa el cliente.
650
         * @throws IOException
651
         * @throws RmfSerializerException
652
         */
653
        public void dataWrite() throws IOException, ProcessInterruptedException,
654
                        OutOfMemoryError {
655
                if (dataWriter == null)
656
                        throw new IOException("No se ha obtenido un objeto de entrada para la escritura valido.");
657

    
658
                write(DefaultRasterWriter.MODE_DATAWRITE);
659

    
660
                if (driverParams.getParamById("tfw") != null &&
661
                                ((ParamImpl)driverParams.getParamById("tfw")).getDefaultValue() instanceof Boolean &&
662
                                ((Boolean) ((ParamImpl)driverParams.getParamById("tfw")).getDefaultValue()).booleanValue() == true)
663
                        if (at != null)
664
                                fileUtil.createWorldFile(this.outFileName, at, sizeWindowX, sizeWindowY);
665

    
666
                if (colorInterp != null)
667
                        try {
668
                                RasterLocator.getManager().getProviderServices().saveObjectToRmfFile(outFileName, DataStoreColorInterpretation.class, colorInterp);
669
                        } catch (RmfSerializerException e) {
670
                                throw new IOException("No se ha podido guardar la interpretacion de color");
671
                        }
672
        }
673

    
674
        /**
675
         * Cancela el salvado de datos.
676
         * @throws GdalException
677
         */
678
        public void writeClose() {
679
                try {
680
                        if(bufBands != null) {
681
                                for (int i = 0; i < bufBands.length; i++) {
682
                                        bufBands[i].buffAPalette = null;
683
                                        bufBands[i].buffBPalette = null;
684
                                        bufBands[i].buffByte = null;
685
                                        bufBands[i].buffShort = null;
686
                                        bufBands[i].buffInt = null;
687
                                        bufBands[i].buffFloat = null;
688
                                        bufBands[i].buffDouble = null;
689
                                }
690
                        }
691
                                
692
                        if(dstDataset != null)
693
                                dstDataset.close();
694
                } catch (GdalException e) {
695
                        e.printStackTrace();
696
                }
697
        }
698
        
699
        /**
700
         * Cancela el salvado de datos.
701
         */
702
        public void writeCancel() {
703
                write = false;
704
        }
705

    
706
        /**
707
         * Obtiene el valor a la variable write que estar? a true cuando se est? escribiendo
708
         *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
709
         * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
710
         * de salida.
711
         * @return True si puede escribirse y false si no puede
712
         */
713
        public boolean isWrite() {
714
                return write;
715
        }
716

    
717
        /**
718
         * Asigna el valor a la variable write que estar? a true cuando se est? escribiendo
719
         *  o puede escribirse la imagen de salida. El cancelar la operaci?n de escritura
720
         * pondr? esta variable a false deteniendose la escritura y cerrandose el dataset
721
         * de salida.
722
         * @param write Variable booleana. True si puede escribirse y false si no puede
723
         */
724
        public void setWrite(boolean write) {
725
                this.write = write;
726
        }
727

    
728
        /**
729
         * Asigna los par?metros del driver modificados por el cliente.
730
         * @param Params
731
         */
732
        public void setParams(Params params) {
733
                if(params instanceof ParamsImpl)
734
                        this.driverParams = (ParamsImpl)params;
735
                else 
736
                        return;
737

    
738
                int blockSize = 256;
739
                try {
740
                        ParamImpl param = (ParamImpl)driverParams.getParamById("blocksize");
741
                        blockSize = Integer.parseInt(param.getList()[((Integer)param.getDefaultValue()).intValue()]);
742
                        nBlocks = (sizeWindowY / blockSize);
743
                        anchoResto = sizeWindowY - (nBlocks * blockSize);
744
                }catch(NumberFormatException e) {
745
                        //Se queda con el valor de inicializaci?n
746
                }
747
        }
748
        
749
        /*
750
         * (non-Javadoc)
751
         * @see java.lang.Object#finalize()
752
         */
753
        protected void finalize() throws Throwable {
754
                drv        = null;
755
                dstDataset = null;
756
                rband      = null;
757
                geot       = null; 
758
                if(bufBands != null) {
759
                        for (int i = 0; i < bufBands.length; i++) {
760
                                bufBands[i].buffAPalette = null;
761
                                bufBands[i].buffBPalette = null;
762
                                bufBands[i].buffByte = null;
763
                                bufBands[i].buffShort = null;
764
                                bufBands[i].buffInt = null;
765
                                bufBands[i].buffFloat = null;
766
                                bufBands[i].buffDouble = null;
767
                        }
768
                }
769
                super.finalize();
770
        }
771
}