Revision 1829

View differences:

org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.reproject/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.raster.tools.algorithm.reproject.RasterReprojectAlgorithmLibrary
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.reproject/src/main/java/org/gvsig/raster/tools/algorithm/reproject/RasterReprojectAlgorithmLibrary.java
1
/*
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.raster.tools.algorithm.reproject;
25

  
26
import org.gvsig.i18n.Messages;
27
import org.gvsig.raster.tools.algorithm.base.RasterBaseAlgorithmLibrary;
28
import org.gvsig.tools.library.AbstractLibrary;
29
import org.gvsig.tools.library.LibraryException;
30

  
31
/**
32
 * Initialization of RasterReprojectAlgorithmLibrary library.
33
 * 
34
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
35
 */
36
public class RasterReprojectAlgorithmLibrary extends AbstractLibrary {
37
	public static final String         PROCESS_LABEL   = "RasterReprojectionProcess";
38
	
39
    @Override
40
    protected void doInitialize() throws LibraryException {
41
        // Nothing to do
42
    }
43

  
44
    @Override
45
    protected void doPostInitialize() throws LibraryException {
46
    	//Registers the process and its parameters
47
    	RasterBaseAlgorithmLibrary.register(PROCESS_LABEL, ReprojectProcess.class);
48
    	ReprojectProcess.registerParameters();
49
    	
50
        Messages.addResourceFamily(
51
            "org.gvsig.raster.tools.algorithm.reproject", 
52
            RasterReprojectAlgorithmLibrary.class.getClassLoader(), 
53
            RasterReprojectAlgorithmLibrary.class.getClass().getName());
54
        //registerGeoProcess(new RasterReprojectAlgorithmLibrary());
55
    }
56
}
0 57

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.reproject/src/main/java/org/gvsig/raster/tools/algorithm/reproject/ReprojectException.java
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.tools.algorithm.reproject;
23

  
24

  
25
/**
26
 * This exception is thrown if happen problems processing data with this algorithm.
27
 * 
28
 * @author Nacho Brodin (nachobrodin@gmail.com)
29
 *
30
 */
31
public class ReprojectException extends Exception {
32
	private static final long serialVersionUID = -3022090543908771484L;
33
	
34
	public ReprojectException(String msg){
35
		super(msg);
36
	}
37
	
38
	public ReprojectException(String msg, Throwable e){
39
		super(msg, e);
40
	}
41
}
0 42

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.reproject/src/main/java/org/gvsig/raster/tools/algorithm/reproject/ReprojectProcess.java
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.tools.algorithm.reproject;
23

  
24
import java.util.HashMap;
25

  
26
import javax.swing.SwingUtilities;
27

  
28
import org.cresques.cts.IProjection;
29
import org.gvsig.fmap.dal.coverage.exception.CloneException;
30
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
31
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
32
import org.gvsig.i18n.Messages;
33
import org.gvsig.raster.tools.algorithm.base.RasterBaseAlgorithmLibrary;
34
import org.gvsig.raster.tools.algorithm.base.process.RasterProcess;
35

  
36
/**
37
 * Process to reproject layers. The size of the new image and the pixel size can
38
 * be passed by parameter. If some of these values are zero everyone are calculated
39
 * automatically
40
 *
41
 * 10/12/2007
42
 * @author Nacho Brodin nachobrodin@gmail.com
43
 */
44
public class ReprojectProcess extends RasterProcess {
45
	public static String[]    INTERP_METHODS  = new String[]{"Nearest", "Bilinear", "InverseDistance"};
46
	
47
	public static String      RASTER_STORE    = "RasterStore";
48
	public static String      PATH            = "Path";
49
	public static String      DST_PROJECTION  = "DST_Projection";
50
	public static String      SRC_PROJECTION  = "SRC_Projection";
51
	public static String      SIZEX           = "SizeX";
52
	public static String      SIZEY           = "SizeY";
53
	public static String      CELLSIZE        = "CellSize";
54
	public static String      FILENAME        = "FileName";
55
	public static String      TIME            = "Time";
56
	public static String      INTERPOLATION   = "Interpolation";
57
	
58
	private RasterDataStore   store          = null;
59
	private String            filename       = null;
60
	private IProjection       projdst        = null;
61
	private IProjection       projsrc        = null;
62
	private Reproject         reproject      = null;
63
	private long              milis          = 0;
64
	private int               w              = 0;
65
	private int               h              = 0;
66
	private double            cellSize       = 0;
67
	private int               interpolation  = 0;
68
	
69
	public static void registerParameters() {
70
		RASTER_STORE = RasterBaseAlgorithmLibrary.registerInputParameter(RASTER_STORE, RasterDataStore.class);
71
		PATH = RasterBaseAlgorithmLibrary.registerInputParameter(PATH, String.class);
72
		DST_PROJECTION = RasterBaseAlgorithmLibrary.registerInputParameter(DST_PROJECTION, IProjection.class);
73
		SRC_PROJECTION = RasterBaseAlgorithmLibrary.registerInputParameter(SRC_PROJECTION, IProjection.class);
74
		SIZEX = RasterBaseAlgorithmLibrary.registerInputParameter(SIZEX, Integer.class);
75
		SIZEY = RasterBaseAlgorithmLibrary.registerInputParameter(SIZEY, Integer.class);
76
		CELLSIZE = RasterBaseAlgorithmLibrary.registerInputParameter(CELLSIZE, Double.class);
77
		INTERPOLATION = RasterBaseAlgorithmLibrary.registerInputParameter(INTERPOLATION, Integer.class); 
78
		
79
		FILENAME = RasterBaseAlgorithmLibrary.registerOutputParameter(FILENAME, String.class);
80
		TIME = RasterBaseAlgorithmLibrary.registerOutputParameter(TIME, Long.class);
81
	}
82
	
83
	/*
84
	 * (non-Javadoc)
85
	 * @see org.gvsig.rastertools.RasterProcess#init()
86
	 */
87
	public void init() {
88
		store = getParam(RASTER_STORE) != null ? (RasterDataStore)getParam(RASTER_STORE) : null;
89
		filename = getStringParam(PATH);
90
		projdst = getParam(DST_PROJECTION) != null ? (IProjection) getParam(DST_PROJECTION) : null;
91
		projsrc = getParam(SRC_PROJECTION) != null ? (IProjection) getParam(SRC_PROJECTION) : null; 
92
		w = getIntParam(SIZEX);
93
		h = getIntParam(SIZEY);
94
		cellSize = getDoubleParam(CELLSIZE);
95
		interpolation = getIntParam(INTERPOLATION);
96
	}
97
	
98
	/**
99
	 * M?todo donde se ejecutar? el Thread, aqu? se reproyecta el raster.
100
	 */
101
	public void process() throws ProcessInterruptedException {
102
		long t1 = new java.util.Date().getTime();
103
		insertLineLog(Messages.getText("reprojecting"));
104
		
105
		try {
106
			store = store.cloneDataStore();
107
		} catch (CloneException e1) {
108
			messageBoxError("error_reprojecting", this, e1);
109
		}
110
		
111
		reproject = new Reproject(store, filename, interpolation, this);
112
		try {
113
			int result = reproject.warp(projdst, projsrc, w, h, cellSize);
114
			if(result != 0) {
115
				if (incrementableTask != null) {
116
					incrementableTask.processFinalize();
117
					setProgressActive(false);
118
				}
119
				messageBoxError("transformation_not_possible", this);
120
				return;
121
			}
122

  
123
			long t2 = new java.util.Date().getTime();
124
			milis = t2 - t1;
125
			
126
			SwingUtilities.invokeLater(new Runnable() {
127
				public void run() {
128
					if (externalActions != null) {
129
						HashMap<String, Object> map = new HashMap<String, Object>();
130
						map.put(FILENAME, filename);
131
						map.put(TIME, new Long(milis));
132
						externalActions.end(map);
133
					}
134
				}
135
			});
136
		} catch (ReprojectException e) {
137
			if (incrementableTask != null)
138
				incrementableTask.processFinalize();
139
			messageBoxError("error_reprojecting", this, e);
140
		}
141
	}
142
	
143
	/*
144
	 * (non-Javadoc)
145
	 * @see org.gvsig.raster.tools.app.basic.raster.process.RasterProcess#getResult()
146
	 */
147
	public Object getResult() {
148
		HashMap<String, Object> map = new HashMap<String, Object>();
149
		map.put(FILENAME, filename);
150
		map.put(TIME, new Long(milis));
151
		return map;
152
	}
153

  
154
	/*
155
	 * (non-Javadoc)
156
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
157
	 */
158
	public int getPercent() {
159
		if(reproject != null)
160
			return reproject.getPercent();
161
		else 
162
			return 0;
163
	}
164

  
165
	/*
166
	 * (non-Javadoc)
167
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
168
	 */
169
	public String getTitle() {
170
		return Messages.getText("reprojecting");
171
	}
172
}
0 173

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.reproject/src/main/java/org/gvsig/raster/tools/algorithm/reproject/Reproject.java
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.tools.algorithm.reproject;
23

  
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.Point2D;
26
import java.io.File;
27

  
28
import org.cresques.cts.ICoordTrans;
29
import org.cresques.cts.IProjection;
30
import org.gvsig.fmap.dal.coverage.RasterLocator;
31
import org.gvsig.fmap.dal.coverage.RasterManager;
32
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
33
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
34
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
35
import org.gvsig.fmap.dal.coverage.datastruct.Params;
36
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
37
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
38
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
39
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
40
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
41
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
42
import org.gvsig.fmap.dal.coverage.store.RasterWriter;
43
import org.gvsig.raster.tools.algorithm.base.process.RasterProcess;
44
import org.gvsig.raster.tools.algorithm.base.util.Interpolation;
45

  
46

  
47
/**
48
 * Reprojects a RasterDataStore. 
49
 *
50
 * @version 30/04/2008
51
 * @author Nacho Brodin nachobrodin@gmail.com
52
 */
53
public class Reproject {
54
	private RasterDataStore   store                 = null;
55
	private String            pathDest              = null;
56
	private int               percent               = 0;
57
	private int               interpolationMethod   = 0;
58
	private Interpolation     interpolation         = null; 
59
	private RasterProcess     process               = null;
60

  
61
	/**
62
	 * Constructor de la clase.
63
	 * @param lyr
64
	 * @param pathDest Ruta de destino
65
	 */
66
	public Reproject(RasterDataStore store, String pathDest, int inter, RasterProcess process) {
67
		this.store = store;
68
		this.pathDest = pathDest;
69
		this.interpolationMethod = inter;
70
		this.process = process;
71
	}
72

  
73
	/**
74
	 * M?todo para la transformaci?n del raster.
75
	 * @param destinationSrs Proyecci?n destino
76
	 */
77
	public int warp(IProjection destinationSrs, IProjection sourceSrs, int w, int h, double cellSize) throws ReprojectException {
78
		if (store == null)
79
			throw new ReprojectException("Capa no valida.");
80
		if (!store.isReproyectable())
81
			throw new ReprojectException("Esta capa no se puede reproyectar.");
82
		if (destinationSrs == null || destinationSrs.getAbrev() == null)
83
			throw new ReprojectException("Proyecci?n de destino no valida.");
84

  
85

  
86
		File file = new File(pathDest);
87
		if (!file.getParentFile().canWrite())
88
			throw new ReprojectException("Ruta de destino no valida.");
89

  
90
		ICoordTrans transf = sourceSrs.getCT(destinationSrs);
91
		Extent bbox = store.getExtent();
92
		Point2D ul = new Point2D.Double(bbox.getULX(), bbox.getULY());
93
		Point2D lr = new Point2D.Double(bbox.getLRX(), bbox.getLRY());
94
		//Point2D p = new Point2D.Double(lyr.getFullRasterExtent().getULX(), lyr.getFullRasterExtent().getULY());
95
		ul = transf.convert(ul, ul);
96
		lr = transf.convert(lr, lr);
97
		Extent newBbox = RasterLocator.getManager().getDataStructFactory().createExtent(ul, lr);
98
		
99
		if(w <= 0 || h <= 0 ) {
100
			double[] size = getSize(bbox, newBbox);
101
			w = (int)size[0];
102
			h = (int)size[1];
103
			cellSize = size[2];
104
		}
105
		int dataType = store.getDataType()[0];
106
		Buffer buf = RasterLocator.getManager().createBuffer(
107
				store.getDataType()[0], w, h, store.getBandCount(), true);
108
		
109
		NoData nd = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(
110
				store.getBandCount(), dataType);
111
		
112
		RasterQuery query = RasterLocator.getManager().createQuery();
113
		query.setAllDrawableBands();
114
		query.setAreaOfInterest();
115
		query.setReadOnly(true);
116
		try {
117
			ICoordTrans t = destinationSrs.getCT(sourceSrs);
118
			Buffer sourceBuffer = store.query(query);
119
			if(interpolationMethod < 0) {
120
				for (int row = 0; row < buf.getHeight(); row++) {
121
					for (int col = 0; col < buf.getWidth(); col++) {
122
						Point2D p = transformPoint(newBbox, col, row, cellSize, t);
123
						writePixel(dataType, sourceBuffer, buf, p, col, row, nd);
124
					}
125
					process.updatePercent(row, buf.getHeight());
126
				}
127
			} else {
128
				interpolation = new Interpolation(sourceBuffer);
129
				for (int row = 0; row < buf.getHeight(); row++) {
130
					for (int col = 0; col < buf.getWidth(); col++) {
131
						Point2D p = transformPoint(newBbox, col, row, cellSize, t);
132
						writePixelInterpolated(dataType, sourceBuffer, buf, p, col, row, nd, interpolationMethod);
133
					}
134
					process.updatePercent(row, buf.getHeight());
135
				}
136
			}
137

  
138
			export(pathDest, buf, cellSize, newBbox.getULX(), newBbox.getULY());
139
		} catch (RasterDriverException e) {
140
			new ReprojectException("", e);
141
		} catch (ProcessInterruptedException e) {
142
		} catch (InvalidSetViewException e) {
143
			new ReprojectException("", e);
144
		}
145
		
146
		return 0;
147
	}
148
	
149
	/**
150
	 * Writes one pixel in the destination buffer
151
	 * @param type
152
	 * @param sourceBuffer
153
	 * @param buf
154
	 * @param p
155
	 * @param col
156
	 * @param row
157
	 */
158
	private void writePixel(int type, Buffer sourceBuffer, Buffer buf, Point2D p, int col, int row, NoData nd) {
159
		if(type == Buffer.TYPE_BYTE) {
160
			if(p.getX() > 0 && p.getX() < sourceBuffer.getWidth() && p.getY() > 0 && p.getY() < sourceBuffer.getHeight())
161
				for (int iBand = 0; iBand < store.getBandCount(); iBand++) {
162
					//if(iBand == 0)
163
						//System.out.println("Row:" + row + " Col:" + col + "  Y:" + (int)p.getY() + " X:" + (int)p.getX());
164
					buf.setElem(row, col, iBand, sourceBuffer.getElemByte((int)p.getY(), (int)p.getX(), iBand));
165
				}
166
			else
167
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
168
					buf.setElem(row, col, iBand, nd.getValue().byteValue());
169
		} else if(type == Buffer.TYPE_DOUBLE) {
170
			if(p.getX() > 0 && p.getX() < sourceBuffer.getWidth() && p.getY() > 0 && p.getY() < sourceBuffer.getHeight())
171
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
172
					buf.setElem(row, col, iBand, sourceBuffer.getElemDouble((int)p.getY(), (int)p.getX(), iBand));
173
			else
174
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
175
					buf.setElem(row, col, iBand, nd.getValue().doubleValue());
176
		} else if(type == Buffer.TYPE_FLOAT) {
177
			if(p.getX() > 0 && p.getX() < sourceBuffer.getWidth() && p.getY() > 0 && p.getY() < sourceBuffer.getHeight())
178
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
179
					buf.setElem(row, col, iBand, sourceBuffer.getElemFloat((int)p.getY(), (int)p.getX(), iBand));
180
			else
181
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
182
					buf.setElem(row, col, iBand, nd.getValue().floatValue());
183
		} else if(type == Buffer.TYPE_SHORT) {
184
			if(p.getX() > 0 && p.getX() < sourceBuffer.getWidth() && p.getY() > 0 && p.getY() < sourceBuffer.getHeight())
185
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
186
					buf.setElem(row, col, iBand, sourceBuffer.getElemShort((int)p.getY(), (int)p.getX(), iBand));
187
			else
188
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
189
					buf.setElem(row, col, iBand, nd.getValue().shortValue());
190
		} else if(type == Buffer.TYPE_INT) {
191
			if(p.getX() > 0 && p.getX() < sourceBuffer.getWidth() && p.getY() > 0 && p.getY() < sourceBuffer.getHeight())
192
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
193
					buf.setElem(row, col, iBand, sourceBuffer.getElemInt((int)p.getY(), (int)p.getX(), iBand));
194
			else
195
				for (int iBand = 0; iBand < store.getBandCount(); iBand++)
196
					buf.setElem(row, col, iBand, nd.getValue().intValue());
197
		} 
198
	}
199
	
200
	/**
201
	 * Writes one pixel in the destination buffer
202
	 * @param type
203
	 * @param sourceBuffer
204
	 * @param buf
205
	 * @param p
206
	 * @param col
207
	 * @param row
208
	 */
209
	private void writePixelInterpolated(int type, Buffer sourceBuffer, Buffer buf, Point2D p, int col, int row, NoData nd, int interpMethod) {
210
		double value = 0;
211
		if(p.getX() > 0 && p.getX() < sourceBuffer.getWidth() && p.getY() > 0 && p.getY() < sourceBuffer.getHeight())
212
			for (int iBand = 0; iBand < store.getBandCount(); iBand++) {
213
				if(interpMethod == 0) //Nearest neighbor
214
					value = interpolation.getNearestNeighbour(p.getX(), p.getY(), iBand);
215
				if(interpMethod == 1) //Bilinear
216
					value = interpolation.getBilinearValue(p.getX(), p.getY(), iBand);
217
				if(interpMethod == 2) //Inverse distance
218
					value = interpolation.getInverseDistance(p.getX(), p.getY(), iBand);
219
				if(type == Buffer.TYPE_BYTE)
220
					buf.setElem(row, col, iBand, (byte)value);
221
				else if(type == Buffer.TYPE_DOUBLE)
222
					buf.setElem(row, col, iBand, (double)value);
223
				else if(type == Buffer.TYPE_FLOAT)
224
					buf.setElem(row, col, iBand, (float)value);
225
				else if(type == Buffer.TYPE_SHORT)
226
					buf.setElem(row, col, iBand, (short)value);
227
				else if(type == Buffer.TYPE_INT)
228
					buf.setElem(row, col, iBand, (int)value);
229
			}
230
		else
231
			for (int iBand = 0; iBand < store.getBandCount(); iBand++) {
232
				if(type == Buffer.TYPE_BYTE)
233
					buf.setElem(row, col, iBand, nd.getValue().byteValue());
234
				else if(type == Buffer.TYPE_DOUBLE)
235
					buf.setElem(row, col, iBand, nd.getValue().doubleValue());
236
				else if(type == Buffer.TYPE_FLOAT)
237
					buf.setElem(row, col, iBand, nd.getValue().floatValue());
238
				else if(type == Buffer.TYPE_SHORT)
239
					buf.setElem(row, col, iBand, nd.getValue().shortValue());
240
				else if(type == Buffer.TYPE_INT)
241
					buf.setElem(row, col, iBand, nd.getValue().intValue());
242
			}
243
	}
244
	
245
	/**
246
	 * Transforms the upper left coordinate of a pixel using the transformation 
247
	 * which is passed by parameter
248
	 * @param p
249
	 * @param newBbox
250
	 * @param col
251
	 * @param row
252
	 * @param cellSize
253
	 * @param t
254
	 */
255
	private Point2D transformPoint(Extent newBbox, int col, int row, double cellSize, ICoordTrans t) {
256
		Point2D p = new Point2D.Double(
257
				newBbox.getULX() + (col * cellSize), 
258
				newBbox.getULY() - (row * cellSize));
259
		p = t.convert(p, p);
260
		p = store.worldToRaster(p);
261
		return p;
262
	}
263
	
264
	/**
265
	 * Gets the size of the new image
266
	 * @param bbox
267
	 * @param newBbox
268
	 * @return
269
	 */
270
	private double[] getSize(Extent bbox, Extent newBbox) {
271
		double sumSideOldBBox = bbox.width() + bbox.height();
272
		double sumSideNewBBox = newBbox.width() + newBbox.height();
273
		double d1x = (bbox.width() * 100) / sumSideOldBBox; 
274
		double d1y = (bbox.height() * 100) / sumSideOldBBox;
275
		double d2x = (newBbox.width() * 100) / sumSideNewBBox;
276
		double d2y = (newBbox.height() * 100) / sumSideNewBBox;
277
		double p2y = (store.getHeight() * d2y) / d1y;
278
		double p2x = (store.getWidth() * d2x) / d1x;
279
		double newCellSize = newBbox.width() / p2x;
280
		return new double[]{Math.round(p2x), Math.round(p2y), newCellSize};
281
	}
282
	
283
	public boolean export(final String sFilename, Buffer buf, double cellsize, double minX, double minY) {
284

  
285
        try {
286
            RasterManager manager = RasterLocator.getManager();
287
            final DataServerWriter writerBufferServer =
288
                manager.createDataServerWriter();
289
            writerBufferServer.setBuffer(buf, -1);
290
            final Params params = manager.createWriterParams(sFilename);
291
            final AffineTransform affineTransform =
292
                new AffineTransform(cellsize, 0, 0,
293
                    -cellsize, minX, minY);
294

  
295
            final RasterWriter writer =
296
                manager.createWriter(writerBufferServer, sFilename,
297
                    buf.getBandCount(), affineTransform, buf.getWidth(),
298
                    buf.getHeight(), buf.getDataType(), params, null);
299
            writer.dataWrite();
300
            writer.writeClose();
301

  
302
        } catch (final Exception e) {
303
        	e.printStackTrace();
304
            return false;
305
        }
306

  
307
        return true;
308

  
309
    }
310

  
311
	/**
312
	 * Obtiene el porcentaje de progreso de la tarea de reproyecci?n para
313
	 * mostrarlo por pantalla.
314
	 * @return
315
	 */
316
	public int getPercent() {
317
		return percent;
318
	}
319
}
0 320

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.reproject/pom.xml
1
<?xml version="1.0" encoding="ISO-8859-1"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
	<modelVersion>4.0.0</modelVersion>
4
	<artifactId>org.gvsig.raster.tools.algorithm.reproject</artifactId>
5
	<packaging>jar</packaging>
6
	<name>org.gvsig.raster.tools.algorithm.reproject</name>
7
	<parent>
8
		<groupId>org.gvsig</groupId>
9
		<artifactId>org.gvsig.raster.tools.algorithm</artifactId>
10
		<version>2.0.1-SNAPSHOT</version>
11
	</parent>
12
    <properties>
13
        <build-dir>${basedir}/../../../build</build-dir>
14
    </properties>
15
    <dependencies>
16
		<dependency>
17
			<groupId>org.gvsig</groupId>
18
			<artifactId>org.gvsig.raster.tools.algorithm.base</artifactId>
19
            <scope>compile</scope>
20
		</dependency>
21
	</dependencies>
22
</project>
0 23

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.saveraster/src/main/java/org/gvsig/raster/tools/algorithm/saveraster/ExternalCancellable.java
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.tools.algorithm.saveraster;
23

  
24
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
25

  
26
public class ExternalCancellable implements org.gvsig.fmap.dal.coverage.store.ExternalCancellable {
27
	private IncrementableTask task = null;
28
	
29
	public ExternalCancellable(IncrementableTask task) {
30
		this.task = task;
31
	}
32
	
33
	/*
34
	 * (non-Javadoc)
35
	 * @see org.gvsig.raster.dataset.io.IExternalCancellable#processFinalize()
36
	 */
37
	public void processFinalize() {
38
		if(task != null)
39
			task.processFinalize();
40
	}
41
}
0 42

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.saveraster/src/main/java/org/gvsig/raster/tools/algorithm/saveraster/SaveRasterAlgorithmLibrary.java
1
/*
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.raster.tools.algorithm.saveraster;
25

  
26
import org.gvsig.i18n.Messages;
27
import org.gvsig.raster.tools.algorithm.base.RasterBaseAlgorithmLibrary;
28
import org.gvsig.tools.library.AbstractLibrary;
29
import org.gvsig.tools.library.LibraryException;
30

  
31
/**
32
 * Initialization of SaveRasterAlgorithmLibrary library.
33
 * 
34
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
35
 */
36
public class SaveRasterAlgorithmLibrary extends AbstractLibrary {
37
	public static final String         PROCESS_LABEL   = "SaveRasterProcess";
38
	
39
    @Override
40
    protected void doInitialize() throws LibraryException {
41
        // Nothing to do
42
    }
43

  
44
    @Override
45
    protected void doPostInitialize() throws LibraryException {
46
    	//Registers the process and its parameters
47
    	RasterBaseAlgorithmLibrary.register(PROCESS_LABEL, SaveRasterProcess.class);
48
    	SaveRasterProcess.registerParameters();
49
    	
50
        Messages.addResourceFamily(
51
            "org.gvsig.raster.tools.algorithm.saveraster", 
52
            SaveRasterAlgorithmLibrary.class.getClassLoader(), 
53
            SaveRasterAlgorithmLibrary.class.getClass().getName());
54
        //registerGeoProcess(new SaveRasterAlgorithmLibrary());
55
    }
56
}
0 57

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.saveraster/src/main/java/org/gvsig/raster/tools/algorithm/saveraster/RasterizeFLayers.java
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.tools.algorithm.saveraster;
23

  
24
import java.awt.Color;
25
import java.awt.Dimension;
26
import java.awt.Graphics2D;
27
import java.awt.geom.Rectangle2D;
28
import java.awt.image.BufferedImage;
29

  
30
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
31
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
32
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
33
import org.gvsig.fmap.dal.exception.ReadException;
34
import org.gvsig.fmap.geom.GeometryLocator;
35
import org.gvsig.fmap.geom.GeometryManager;
36
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
37
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
38
import org.gvsig.fmap.geom.primitive.Envelope;
39
import org.gvsig.fmap.mapcontext.ViewPort;
40
import org.gvsig.fmap.mapcontext.impl.DefaultMapContextDrawer;
41
import org.gvsig.fmap.mapcontext.layers.FLayers;
42
import org.gvsig.gui.beans.incrementabletask.IIncrementable;
43
import org.gvsig.i18n.Messages;
44
import org.gvsig.raster.fmap.layers.FLyrRaster;
45
import org.gvsig.raster.tools.algorithm.base.process.RasterProcess;
46
import org.gvsig.tools.task.Cancellable;
47
import org.slf4j.Logger;
48
import org.slf4j.LoggerFactory;
49

  
50
/**
51
 * Sirve datos solicitados por los drivers que salvan a raster. Hereda de
52
 * Rasterizer y reescribe el m?todo readData que es el que ser? llamado desde el
53
 * driver cada vez que vacie el buffer y necesite m?s datos.
54
 *
55
 * @version 04/06/2007
56
 * @author Nacho Brodin (nachobrodin@gmail.com)
57
 */
58
@SuppressWarnings("deprecation")
59
public class RasterizeFLayers implements DataServerWriter, IIncrementable {
60
	private static final GeometryManager 	geomManager		= GeometryLocator.getGeometryManager();
61
	private Logger                          logger          = LoggerFactory.getLogger(RasterProcess.class.toString());
62
	
63
	private ViewPort						viewPort 		= null;
64
	private ViewPort						viewPortBlock	= null;
65
	private FLayers							flayers 		= null;
66
	private Color							backgroundColor = null;
67
	private boolean							firstRead 		= true;
68
	private int 							nBlocks 		= 0;
69
//	private double 							percentMax 		= 100.0D;
70
	protected double 						wcIntervalo 	= 0;
71
	protected Dimension 					dimension 		= null;
72
	protected int 							blockSize 		= 0;
73
	protected double 						wcAlto 			= 0;
74
	protected int 							lastBlock 		= 0;
75
	protected BufferedImage 				image 			= null;
76
	protected int[] 						rasterData 		= null;
77
	protected int 							contBlocks 		= 1;
78
	protected int							percent 		= 0;
79
	protected int							imgHeight 		= 0;
80

  
81
	/**
82
	 * Calculo del viewPort
83
	 * @param vp
84
	 */
85
	private void calcViewPort(ViewPort vp) {
86
		Rectangle2D ext = null;
87

  
88
		if (viewPortBlock == null)
89
			ext = new Rectangle2D.Double(	vp.getExtent().getMinX(),
90
											vp.getExtent().getMaxY() - wcIntervalo,
91
											vp.getExtent().getWidth(),
92
											wcIntervalo
93
										);
94
		else
95
			ext = new Rectangle2D.Double(	viewPortBlock.getExtent().getMinX(),
96
											viewPortBlock.getExtent().getMinY() - wcIntervalo,
97
											viewPortBlock.getExtent().getWidth(),
98
											wcIntervalo
99
										);
100

  
101
		viewPortBlock = new ViewPort(vp.getProjection());
102
		Envelope env;
103
		try {
104
			env = geomManager.createEnvelope(ext.getMinX(), ext.getMinY(), ext.getMaxX(), ext.getMaxY(), SUBTYPES.GEOM2D);
105
			viewPortBlock.setEnvelope(env);
106
		} catch (CreateEnvelopeException e) {
107
			logger.debug("Error creating the envelope", null, e);
108
		}		
109
		viewPortBlock.setImageSize(dimension);
110
		viewPortBlock.refreshExtent();
111
	}
112

  
113
	/**
114
	 * Constructor
115
	 * @param flyrs capas
116
	 * @param vp viewport
117
	 * @param blockSize altura del bloque que se lee de una vez en la imagen de entrada
118
	 * @param mapCtrl Mapcontrol
119
	 */
120
	public RasterizeFLayers(FLayers flyrs, ViewPort vp, int blockSize) {
121
		this.blockSize = blockSize;
122
		backgroundColor = vp.getBackColor();
123
		viewPort = new ViewPort(vp.getProjection());
124
		viewPort.setImageSize(vp.getImageSize());
125
		/*Rectangle2D ex = vp.getExtent();
126
		Envelope env = null;
127
		try {
128
			env = geomManager.createEnvelope(ex.getMinX(), ex.getMinY(), ex.getMaxX(), ex.getMaxY(), SUBTYPES.GEOM2D);
129
			//viewPortBlock = new ViewPort(vp.getProjection());
130
			//viewPortBlock.setEnvelope(env);
131
		} catch (CreateEnvelopeException e) {
132
			logger.debug("Error creating the envelope", null, e);
133
		}*/
134
		
135

  
136
		// Calculo del viewPort del primer bloque
137
		viewPort.setEnvelope(vp.getAdjustedExtent());
138
		wcAlto = viewPort.getExtent().getMaxY() - viewPort.getExtent().getMinY();
139
		wcIntervalo = (blockSize * wcAlto) / viewPort.getImageHeight();
140
		dimension = new Dimension(viewPort.getImageWidth(), blockSize);
141

  
142
		imgHeight = vp.getImageHeight();
143
		nBlocks = (vp.getImageHeight() / blockSize);
144

  
145
		// Tama?o de ?ltimo bloque en pixeles
146
		lastBlock = vp.getImageHeight() - (nBlocks * blockSize);
147

  
148
		calcViewPort(viewPort);
149

  
150
		this.flayers = flyrs;
151
	}
152

  
153
	/**
154
	 * Compatibilidad con el piloto de raster
155
	 * @see readData
156
	 */
157
	public int[] readARGBData(int sX, int sY, int nBand) throws ProcessInterruptedException, OutOfMemoryError {
158
		return readData( sX, sY, nBand);
159
	}
160

  
161
	public int[] readData(int sX, int sY, int nBand) throws ProcessInterruptedException, OutOfMemoryError {
162
		if (nBand == 0) { // Con nBand==0 se devuelven las 3 bandas
163
			nBlocks = (int) Math.ceil(imgHeight / (double) blockSize);
164
			image = new BufferedImage(sX, sY, BufferedImage.TYPE_INT_ARGB);
165
			Graphics2D g = (Graphics2D) image.getGraphics();
166
			g.setColor(backgroundColor);
167
			g.fillRect(0, 0, viewPortBlock.getImageWidth(), viewPortBlock.getImageHeight());
168
			try {
169
				// TODO: FUNCIONALIDAD: Salvar los m?ximos y m?nimos para salvar 16 bits
170

  
171
				// Si es la primera lectura salvamos los valores de m?ximo y m?nimo para la aplicaci?n
172
				// de realce si la imagen es de 16 bits.
173
				if (firstRead) {
174
					for (int i = 0; i < flayers.getLayersCount(); i++)
175
						if (flayers.getLayer(i) instanceof FLyrRaster) {
176
							FLyrRaster raster = (FLyrRaster) flayers.getLayer(i);
177
							if (raster.getDataStore().getDataType()[0] == Buffer.TYPE_SHORT || raster.getDataStore().getDataType()[0] == Buffer.TYPE_USHORT) {
178
								//Statistic stats = raster.getSource().getFilterStack().getStats();
179
								//stats.history.add(stats.new History(raster.getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
180
							}
181
						}
182
					firstRead = false;
183
				}
184

  
185
				DefaultMapContextDrawer mapContextDrawer = new DefaultMapContextDrawer();
186
				mapContextDrawer.setMapContext(flayers.getMapContext());
187
				mapContextDrawer.setViewPort(viewPortBlock);
188
				mapContextDrawer.draw(flayers, image, g, new Cancellable(){
189
					public boolean isCanceled() {
190
						return false;
191
					}
192

  
193
					public void setCanceled(boolean canceled) {
194
					}
195
				}, flayers.getMapContext().getScaleView());
196

  
197
				// Si es el ?ltimo bloque vaciamos el historial de m?ximos y m?nimos
198
				if ((contBlocks + 1) == nBlocks)
199
					for (int i = 0; i < flayers.getLayersCount(); i++)
200
						if (flayers.getLayer(i) instanceof FLyrRaster) {
201
							FLyrRaster raster = (FLyrRaster) flayers.getLayer(i);
202
							if (raster.getDataStore().getDataType()[0] == Buffer.TYPE_SHORT || raster.getDataStore().getDataType()[0] == Buffer.TYPE_USHORT) {
203
								//raster.getDatasource().getFilterStack().getStats().history.clear();
204
								//Statistic stats = raster.getSource().getFilterStack().getStats();
205
							}
206
						}
207

  
208
			} catch (ReadException e) {
209
				logger.debug("Error en el draw de capa", e);
210
			}
211
			rasterData = image.getRGB(0, 0, sX, sY, rasterData, 0, sX);
212

  
213
			// Calculamos el viewPort del sgte bloque
214

  
215
			if (((contBlocks + 1) * blockSize) <= viewPort.getImageHeight())
216
				dimension = new Dimension(sX, sY);
217
			else { // Calculo de la altura del ?ltimo bloque
218
				dimension = new Dimension(sX, (viewPort.getImageHeight() - (contBlocks * blockSize)));
219
				wcIntervalo = (lastBlock * wcAlto) / viewPort.getImageHeight();
220
			}
221

  
222
			calcViewPort(viewPortBlock);
223

  
224
			percent = ((100 * (contBlocks)) / nBlocks);
225
			contBlocks++;
226

  
227
			return rasterData;
228
		}
229

  
230
		return null;
231
	}
232

  
233
	/**
234
	 * Asigna el ancho del bloque
235
	 * @param sizeBlock Ancho del bloque en pixeles
236
	 */
237
	public void setBlockSize(int blockSize) {
238
		this.blockSize = blockSize;
239
	}
240

  
241
	/**
242
	 * No tiene uso en RasterizerLayer
243
	 */
244
	public byte[][] readByteData(int sizeX, int sizeY) {
245
		return null;
246
	}
247

  
248
	/**
249
	 * No tiene uso en RasterizerLayer
250
	 */
251
	public double[][] readDoubleData(int sizeX, int sizeY) {
252
		return null;
253
	}
254

  
255
	/**
256
	 * No tiene uso en RasterizerLayer
257
	 */
258
	public float[][] readFloatData(int sizeX, int sizeY) {
259
		return null;
260
	}
261

  
262
	/**
263
	 * No tiene uso en RasterizerLayer
264
	 */
265
	public int[][] readIntData(int sizeX, int sizeY) {
266
		return null;
267
	}
268

  
269
	/**
270
	 * No tiene uso en RasterizerLayer
271
	 */
272
	public short[][] readShortData(int sizeX, int sizeY) {
273
		return null;
274
	}
275

  
276
	public String getTitle() {
277
		return Messages.getText("salvando_raster");
278
	}
279

  
280
	public String getLog() {
281
		return Messages.getText("salvando_bloque") + " " + Math.min(nBlocks, contBlocks) + " " + Messages.getText("de") + " " + nBlocks;
282
	}
283

  
284
	public String getLabel() {
285
		return Messages.getText("rasterizando") + "...";
286
	}
287

  
288
	public int getPercent() {
289
		return percent;
290
	}
291

  
292
	public boolean isCancelable() {
293
		return true;
294
	}
295

  
296
	public boolean isPausable() {
297
		return false;
298
	}
299

  
300
	public void setAlphaBuffer(Buffer alphaBuffer) {
301
	}
302

  
303
	public void setBuffer(Buffer buffer, int nband) {
304
	}
305
	
306
	public Buffer getBuffer() {
307
		return null;
308
	}
309

  
310
	public void setBand(int nband) {
311
	}
312

  
313
	public void dispose() {
314
	}
315

  
316
	public Buffer getSource() {
317
		return null;
318
	}
319

  
320
	public void setPercent(int value) {
321
	}
322
}
0 323

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.saveraster/src/main/java/org/gvsig/raster/tools/algorithm/saveraster/SaveRasterProcess.java
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.tools.algorithm.saveraster;
23

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

  
30
import org.cresques.cts.IProjection;
31
import org.gvsig.fmap.dal.coverage.RasterLocator;
32
import org.gvsig.fmap.dal.coverage.RasterManager;
33
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
34
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
35
import org.gvsig.fmap.dal.coverage.datastruct.Params;
36
import org.gvsig.fmap.dal.coverage.datastruct.ViewPortData;
37
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
38
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
39
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
40
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
41
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
42
import org.gvsig.fmap.dal.coverage.store.RasterWriter;
43
import org.gvsig.fmap.dal.coverage.util.CRSUtils;
44
import org.gvsig.fmap.geom.primitive.Envelope;
45
import org.gvsig.fmap.mapcontext.ViewPort;
46
import org.gvsig.fmap.mapcontext.layers.FLayers;
47
import org.gvsig.raster.tools.algorithm.base.RasterBaseAlgorithmLibrary;
48
import org.gvsig.raster.tools.algorithm.base.process.ProcessException;
49
import org.gvsig.raster.tools.algorithm.base.process.RasterProcess;
50

  
51
/**
52
 * Thread que se encarga de llamar a los writer para realizar la tarea de
53
 * salvado y/p compresi?n
54
 *
55
 * @author Nacho Brodin (nachobrodin@gmail.com)
56
 */
57
public class SaveRasterProcess extends RasterProcess {
58
	public static String      VIEWPORT          = "ViewPort";
59
	public static String      PATH              = "Path";
60
	public static String      DIMENSION         = "Dimension";
61
	public static String      BLOCKSIZE         = "Blocksize";
62
	public static String      FILENAME          = "FileName";
63
	public static String      PARAMS            = "WriterParams";
64
	public static String      FLYRS             = "FLyrs";
65
	public static String      TIME              = "Time";
66
	public static String      PROJECTION        = "Projection";
67
	
68
	private IProjection       projection        = null;
69
	private ViewPort          viewPort          = null;
70
	private Dimension         dimension         = null;
71
	private RasterizeFLayers  rasterizerLayer   = null;
72
	private String            fileName          = "";
73
	private Params            writerParams      = null;
74
	//private CopyDataset       jp2Copy           = null;
75
	private boolean           supportImage      = false;
76
	private RasterManager     rManager          = RasterLocator.getManager();
77
	//private Logger            logger            = LoggerFactory.getLogger(RasterProcess.class.toString());
78
	
79
	public static void registerParameters() {
80
		VIEWPORT = RasterBaseAlgorithmLibrary.registerInputParameter(VIEWPORT, ViewPort.class);
81
		PATH = RasterBaseAlgorithmLibrary.registerInputParameter(PATH, String.class);
82
		DIMENSION = RasterBaseAlgorithmLibrary.registerInputParameter(DIMENSION, Dimension.class);
83
		FLYRS = RasterBaseAlgorithmLibrary.registerInputParameter(FLYRS, FLayers.class);
84
		PARAMS = RasterBaseAlgorithmLibrary.registerInputParameter(PARAMS, Params.class);
85
		PROJECTION = RasterBaseAlgorithmLibrary.registerOutputParameter(PROJECTION, IProjection.class);
86
		
87
		FILENAME = RasterBaseAlgorithmLibrary.registerOutputParameter(FILENAME, String.class);
88
		TIME = RasterBaseAlgorithmLibrary.registerOutputParameter(TIME, Long.class);
89
	}
90
	
91
	public void init() {
92
		viewPort = getParam(VIEWPORT) != null ? (ViewPort)getParam(VIEWPORT) : null;
93
		dimension = getParam(DIMENSION) != null ? (Dimension) getParam(DIMENSION) : null;
94
		FLayers flyrs = getParam(FLYRS) != null ? (FLayers) getParam(FLYRS) : null;
95
		int blockSize = getIntParam(BLOCKSIZE);
96
		rasterizerLayer = new RasterizeFLayers(flyrs, viewPort, blockSize);
97
		fileName = getStringParam(FILENAME);
98
		writerParams = getParam(PARAMS) != null ? (Params) getParam(PARAMS) : null;
99
		projection = getParam(PROJECTION) != null ? (IProjection) getParam(PROJECTION) : null;
100
		//supportImage = getBooleanParam("remotelayers") && fileName.endsWith(".jp2");
101
	}
102

  
103
	/**
104
	 * Procesos de escritura de una porci?n de la vista.
105
	 */
106
	public void process() throws ProcessInterruptedException, ProcessException {
107
		TaskEventManager task = rManager.getRasterTask();
108
		
109
		//jp2Copy = null;
110
		long t2;
111
		long t1 = new java.util.Date().getTime();
112
		
113
		//Creamos el driver
114
		Envelope env = viewPort.getAdjustedEnvelope();
115
		Extent ex = rManager.getDataStructFactory().createExtent(env.getMinimum(0), env.getMaximum(1), env.getMaximum(0), env.getMinimum(1));
116
		Dimension imgSz = viewPort.getImageSize();
117
		ViewPortData vpData = rManager.createViewPortData(viewPort.getProjection(), ex, imgSz );
118
		AffineTransform at = new AffineTransform(vpData.getExtent().width() / imgSz.width,
119
												 0, 0,
120
												 -(vpData.getExtent().height() / imgSz.height),
121
												 vpData.getExtent().getULX(),
122
												 vpData.getExtent().getULY());
123
		String oldFileName = fileName;
124
		if(supportImage) {
125
			fileName = fileName.substring(0, Math.min(fileName.lastIndexOf(File.separator) + 1, fileName.length() - 1));
126
			fileName += rManager.getFileUtils().usesOnlyLayerName() + ".tif";
127
			writerParams = getWriterParams(fileName);
128
		}
129

  
130
		//Ejecutamos el driver con los datos pasados
131
		try {
132
			write(fileName, at, writerParams, rasterizerLayer);
133

  
134
			if(task.getEvent() != null)
135
				task.manageEvent(task.getEvent());
136
			
137
			/*if(supportImage) {
138
				try {
139
					insertLineLog(Messages.getText("saving_jp2"));
140
					jp2Copy = new CopyDataset(fileName, oldFileName, incrementableTask);
141
					jp2Copy.copy();
142
					new File(fileName).delete();
143
					new File(rManager.getFileUtils().getRMFNameFromFileName(fileName)).delete();
144
				} catch (LoadLayerException e) {
145
					throw new ProcessException("error_processing", e);
146
				} 
147
				jp2Copy = null;
148
			} */
149
			t2 = new Date().getTime();
150
			try {
151
				saveRasterFinalize(oldFileName, (t2 - t1));
152
			} catch(ArrayIndexOutOfBoundsException exc) {
153
				//Si la ventana se ha cerrado ya es porque ha sido cancelada por lo que
154
				//producir? esta excepci?n. En este caso no se lanza la ventana de informaci?n
155
				//de finalizaci?n.
156
			}
157

  
158
		} catch(IOException ev) {
159
			throw new ProcessException("error_processing", ev);
160
		} catch(OutOfMemoryError ev) {
161
			throw new ProcessException("memoria_excedida", ev);
162
		} finally {
163
			if (incrementableTask != null) {
164
				incrementableTask.processFinalize();
165
				incrementableTask = null;
166
			}
167
		}
168
	}
169
	
170
	/**
171
	 * 
172
	 * @param name
173
	 * @param at
174
	 * @throws IOException
175
	 * @throws ProcessException 
176
	 * @throws InterruptedException
177
	 */
178
	private void write(String name, AffineTransform at, Params writerParams, DataServerWriter rasterizerLayer) throws IOException, ProcessInterruptedException, ProcessException {
179
		//TODO: Usar el nuevo API basado en NewRasterStoreParameters y DataServerExplorer. Ejemplo en ClippingProcess
180
		
181
		TaskEventManager task = rManager.getRasterTask();
182
		RasterWriter geoRasterWriter = null;
183
		try {
184
			//TODO: FUNCIONALIDAD: Poner los gerWriter con la proyecci?n de la vista
185
			geoRasterWriter = rManager.createWriter(rasterizerLayer, name,
186
												3, at, dimension.width,
187
												dimension.height, Buffer.TYPE_IMAGE, writerParams, null);
188
			CRSUtils crsUtil = RasterLocator.getManager().getCRSUtils();
189
			geoRasterWriter.setWkt(crsUtil.convertIProjectionToWkt(projection));
190
		} catch (NotSupportedExtensionException e) {
191
			throw new ProcessException("extension_no_soportada", e);
192
		} catch (RasterDriverException e) {
193
			throw new ProcessException("no_driver_escritura", e);
194
		}
195
		
196
		if(task.getEvent() != null)
197
			task.manageEvent(task.getEvent());
198
		
199
		geoRasterWriter.setCancellableRasterDriver(new ExternalCancellable(incrementableTask));
200
		geoRasterWriter.dataWrite();
201
		geoRasterWriter.writeClose();
202
	}
203
	
204
	/**
205
	 * Obtiene los par?metros del driver de escritura. Si el driver no se ha creado a?n se obtienen
206
	 * unos par?metros con la inicializaci?n por defecto. Si se ha creado ya y se han modificado se
207
	 * devuelven los par?metros con las modificaciones. Si se cambia de driver se devolver? un WriterParams
208
	 * como si fuera la primera vez que se abre.
209
	 * @param name Nombre del fichero sobre el que se salva.
210
	 * @return WriterParams
211
	 */
212
	private Params getWriterParams(String name) throws ProcessException {
213
		RasterWriter writer = null;
214
		String ext = rManager.getFileUtils().getExtensionFromFileName(name);
215
		try {
216
			if(writer == null) //La primera vez que se obtiene el driver
217
				writer = rManager.createWriter(name);
218
			else {
219
				String newType = rManager.getProviderServices().getWriteDriverType(ext);
220
				String oldType = writer.getDriverName();
221
				if(!newType.equals(oldType))  //Cambio de driver despu?s de haber seleccionado y modificado las propiedades de uno
222
					writer = rManager.createWriter(name);
223
			}
224

  
225
			if(writer == null)
226
				throw new ProcessException("no_driver_escritura");
227

  
228
			return writer.getParams();
229

  
230
		} catch (NotSupportedExtensionException e1) {
231
			throw new ProcessException("no_driver_escritura", e1);
232
		} catch (RasterDriverException e1) {
233
			throw new ProcessException("no_driver_escritura", e1);
234
		}
235
	}
236

  
237
	/**
238
	 * Acciones que se realizan al finalizar de salvar a raster.
239
	 * @param fileName Nombre del fichero
240
	 * @param milis Tiempo que ha tardado en ejecutarse
241
	 */
242
	private void saveRasterFinalize(String fileName, long milis) {
243
		if (incrementableTask != null)
244
			incrementableTask.hideWindow();
245
		externalActions.end(new Object[]{fileName, new Long(milis)});
246
	}
247

  
248
	/*
249
	 * (non-Javadoc)
250
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
251
	 */
252
	public int getPercent() {
253
		if(rasterizerLayer != null)
254
			return rasterizerLayer.getPercent();
255
		return 0;
256
	}
257

  
258
	/*
259
	 * (non-Javadoc)
260
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
261
	 */
262
	public String getTitle() {
263
		if(rasterizerLayer != null)
264
			return rasterizerLayer.getTitle();
265
		return null;
266
	}
267
	
268
	/*
269
	 * (non-Javadoc)
270
	 * @see org.gvsig.rastertools.RasterProcess#getLog()
271
	 */
272
	public String getLog() {
273
		if(rasterizerLayer != null)
274
			return rasterizerLayer.getLog();
275
		return null;
276
	}
277
	
278
	/*
279
	 * (non-Javadoc)
280
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel()
281
	 */
282
	public String getLabel() {
283
		if(rasterizerLayer != null)
284
			return rasterizerLayer.getLabel();
285
		return null;
286
	}
287
}
0 288

  
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.saveraster/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.raster.tools.algorithm.saveraster.SaveRasterAlgorithmLibrary
org.gvsig.raster.tools/tags/buildNumber_23/org.gvsig.raster.tools/org.gvsig.raster.tools.algorithm/org.gvsig.raster.tools.algorithm.saveraster/pom.xml
1
<?xml version="1.0" encoding="ISO-8859-1"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
	<modelVersion>4.0.0</modelVersion>
4
	<artifactId>org.gvsig.raster.tools.algorithm.saveraster</artifactId>
5
	<packaging>jar</packaging>
6
	<name>org.gvsig.raster.tools.algorithm.saveraster</name>
7
	<parent>
8
		<groupId>org.gvsig</groupId>
9
		<artifactId>org.gvsig.raster.tools.algorithm</artifactId>
10
		<version>2.0.1-SNAPSHOT</version>
11
	</parent>
12
    <properties>
13
        <build-dir>${basedir}/../../../build</build-dir>
14
    </properties>
15
    <dependencies>
16
		<dependency>
17
			<groupId>org.gvsig</groupId>
18
			<artifactId>org.gvsig.raster.tools.algorithm.base</artifactId>
19
            <scope>compile</scope>
20
		</dependency>
21
		<!--Dependencia debido a que este algoritmo rasteriza capas de gvSIG.-->
22
		<dependency>
23
			<groupId>org.gvsig</groupId>
24
			<artifactId>org.gvsig.raster.fmap</artifactId>
25
            <scope>compile</scope>
26
		</dependency>
27
		<dependency>
28
			<groupId>org.gvsig</groupId>
29
			<artifactId>org.gvsig.fmap.mapcontext</artifactId>
30
            <scope>compile</scope>
31
		</dependency>
32
	</dependencies>
33
</project>
0 34

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff