svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / clipping / ClippingProcess.java @ 19145
History | View | Annotate | Download (13.7 KB)
1 |
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
|
---|---|
2 |
*
|
3 |
* Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
|
4 |
*
|
5 |
* This program is free software; you can redistribute it and/or
|
6 |
* modify it under the terms of the GNU General Public License
|
7 |
* as published by the Free Software Foundation; either version 2
|
8 |
* of the License, or (at your option) any later version.
|
9 |
*
|
10 |
* This program is distributed in the hope that it will be useful,
|
11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
13 |
* GNU General Public License for more details.
|
14 |
*
|
15 |
* You should have received a copy of the GNU General Public License
|
16 |
* along with this program; if not, write to the Free Software
|
17 |
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
|
18 |
*/
|
19 |
package org.gvsig.rastertools.clipping; |
20 |
|
21 |
import java.awt.geom.AffineTransform; |
22 |
import java.io.File; |
23 |
import java.io.FileNotFoundException; |
24 |
import java.io.IOException; |
25 |
|
26 |
import org.apache.log4j.Logger; |
27 |
import org.gvsig.fmap.raster.layers.FLyrRasterSE; |
28 |
import org.gvsig.raster.Configuration; |
29 |
import org.gvsig.raster.RasterProcess; |
30 |
import org.gvsig.raster.buffer.BufferFactory; |
31 |
import org.gvsig.raster.buffer.BufferInterpolation; |
32 |
import org.gvsig.raster.buffer.RasterBuffer; |
33 |
import org.gvsig.raster.buffer.WriterBufferServer; |
34 |
import org.gvsig.raster.dataset.GeoRasterWriter; |
35 |
import org.gvsig.raster.dataset.IBuffer; |
36 |
import org.gvsig.raster.dataset.IRasterDataSource; |
37 |
import org.gvsig.raster.dataset.InvalidSetViewException; |
38 |
import org.gvsig.raster.dataset.NotSupportedExtensionException; |
39 |
import org.gvsig.raster.dataset.Params; |
40 |
import org.gvsig.raster.dataset.RasterDataset; |
41 |
import org.gvsig.raster.dataset.io.RasterDriverException; |
42 |
import org.gvsig.raster.dataset.io.rmf.RmfBlocksManager; |
43 |
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation; |
44 |
import org.gvsig.raster.datastruct.ColorTable; |
45 |
import org.gvsig.raster.datastruct.serializer.ColorTableRmfSerializer; |
46 |
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer; |
47 |
import org.gvsig.raster.grid.GridPalette; |
48 |
import org.gvsig.raster.grid.filter.RasterFilterList; |
49 |
import org.gvsig.raster.grid.filter.bands.ColorTableFilter; |
50 |
import org.gvsig.raster.util.RasterNotLoadException; |
51 |
import org.gvsig.raster.util.RasterToolsUtil; |
52 |
import org.gvsig.raster.util.RasterUtilities; |
53 |
/**
|
54 |
* <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
|
55 |
* para calcular el recorte de una capa.
|
56 |
*
|
57 |
* @version 24/04/2007
|
58 |
* @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
|
59 |
*/
|
60 |
public class ClippingProcess extends RasterProcess { |
61 |
private String fileName = ""; |
62 |
private WriterBufferServer writerBufferServer = null; |
63 |
private FLyrRasterSE rasterSE = null; |
64 |
private AffineTransform affineTransform = new AffineTransform(); |
65 |
private boolean oneLayerPerBand = false; |
66 |
private int[] drawableBands = { 0, 1, 2 }; |
67 |
private int[] dValues = null; |
68 |
private GeoRasterWriter grw = null; |
69 |
private int interpolationMethod = BufferInterpolation.INTERPOLATION_Undefined; |
70 |
private String viewName = ""; |
71 |
private Params params = null; |
72 |
private DatasetColorInterpretation colorInterp = null; |
73 |
|
74 |
/**
|
75 |
* Variables de la resoluci?n de salida
|
76 |
*/
|
77 |
private int resolutionWidth = 0; |
78 |
private int resolutionHeight = 0; |
79 |
|
80 |
private IBuffer buffer = null; |
81 |
|
82 |
/**
|
83 |
* Par?metros obligatorios al proceso:
|
84 |
* <UL>
|
85 |
* <LI>filename: Nombre del fichero de salida</LI>
|
86 |
* <LI>datawriter: Escritor de datos</LI>
|
87 |
* <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso</LI>
|
88 |
* <LI>pixelcoordinates: Coordenadas pixel del recorte</LI>
|
89 |
* <LI>layer: Capa de entrada para el recorte</LI>
|
90 |
* <LI>drawablebands: Bandas de entrada</LI>
|
91 |
* <LI>onelayerperband: booleano que informa de si escribimos una banda por fichero de salida o todas en un fichero</LI>
|
92 |
* <LI>interpolationmethod: M?todo de interpolaci?n.</LI>
|
93 |
* <LI>affinetransform: Transformaci?n que informa al dataset de salida de su referencia geografica</LI>
|
94 |
* <LI>resolution: Ancho y alto de la capa de salida</LI>
|
95 |
* </UL>
|
96 |
*/
|
97 |
public void init() { |
98 |
fileName = getStringParam("filename");
|
99 |
writerBufferServer = (WriterBufferServer) getParam("datawriter");
|
100 |
viewName = getStringParam("viewname");
|
101 |
dValues = getIntArrayParam("pixelcoordinates");
|
102 |
rasterSE = getLayerParam("layer");
|
103 |
drawableBands = getIntArrayParam("drawablebands");
|
104 |
oneLayerPerBand = getBooleanParam("onelayerperband");
|
105 |
interpolationMethod = getIntParam("interpolationmethod");
|
106 |
affineTransform = (AffineTransform)getParam("affinetransform"); |
107 |
colorInterp = (DatasetColorInterpretation)getParam("colorInterpretation");
|
108 |
if(getIntArrayParam("resolution") != null) { |
109 |
resolutionWidth = getIntArrayParam("resolution")[0]; |
110 |
resolutionHeight = getIntArrayParam("resolution")[1]; |
111 |
} |
112 |
params = (Params) getParam("driverparams");
|
113 |
} |
114 |
|
115 |
/**
|
116 |
* Salva la tabla de color al fichero rmf.
|
117 |
* @param fName
|
118 |
* @throws IOException
|
119 |
*/
|
120 |
private void saveToRmf(String fileName) { |
121 |
fileName = RasterUtilities.getNameWithoutExtension(fileName) + ".rmf";
|
122 |
|
123 |
RasterDataset rds = null;
|
124 |
int limitNumberOfRequests = 20; |
125 |
while (rds == null && limitNumberOfRequests > 0) { |
126 |
try {
|
127 |
rds = rasterSE.getDataSource().getDataset(0)[0]; |
128 |
} catch (IndexOutOfBoundsException e) { |
129 |
//En ocasiones, sobre todo con servicios remotos al pedir un datasource da una excepci?n de este tipo
|
130 |
//se supone que es porque hay un refresco en el mismo momento de la petici?n por lo que como es m?s lento de
|
131 |
//gestionar pilla a la capa sin datasources asociados ya que est? reasignandolo. Si volvemos a pedirlo debe
|
132 |
//haberlo cargado ya.
|
133 |
try {
|
134 |
Thread.sleep(200); |
135 |
} catch (InterruptedException e1) { |
136 |
} |
137 |
} |
138 |
limitNumberOfRequests--; |
139 |
} |
140 |
|
141 |
if (rds == null) { |
142 |
//RasterToolsUtil.messageBoxError("error_load_layer", this, new Exception("Error writing RMF. limitNumberOfRequests=" + limitNumberOfRequests));
|
143 |
return;
|
144 |
} |
145 |
|
146 |
RmfBlocksManager manager = rds.getRmfBlocksManager(); |
147 |
|
148 |
RasterFilterList rasterFilterList = rasterSE.getRenderFilterList(); |
149 |
|
150 |
manager.setPath(fileName); |
151 |
|
152 |
if (!manager.checkRmf())
|
153 |
return;
|
154 |
|
155 |
// A?adimos el serializador de NoData
|
156 |
if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) { |
157 |
NoDataRmfSerializer ser = new NoDataRmfSerializer(Double.valueOf(rasterSE.getNoDataValue(0))); |
158 |
manager.addClient(ser); |
159 |
} |
160 |
|
161 |
// A?adimos el serializador para tablas de color
|
162 |
ColorTableFilter colorTableFilter = (ColorTableFilter) rasterFilterList.getByName(ColorTableFilter.names[0]);
|
163 |
if (colorTableFilter != null) { |
164 |
GridPalette gridPalette = new GridPalette((ColorTable) colorTableFilter.getColorTable().clone());
|
165 |
ColorTableRmfSerializer ser = new ColorTableRmfSerializer(gridPalette);
|
166 |
manager.addClient(ser); |
167 |
} |
168 |
|
169 |
try {
|
170 |
manager.write(true);
|
171 |
} catch (FileNotFoundException e) { |
172 |
RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e); |
173 |
} catch (IOException e) { |
174 |
RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e); |
175 |
} |
176 |
|
177 |
manager.deleteAllClients(); |
178 |
} |
179 |
|
180 |
/**
|
181 |
* Tarea de recorte
|
182 |
*/
|
183 |
public void process() throws InterruptedException { |
184 |
IRasterDataSource dsetCopy = null;
|
185 |
try {
|
186 |
long t2;
|
187 |
long t1 = new java.util.Date().getTime(); |
188 |
|
189 |
insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster")); |
190 |
|
191 |
dsetCopy = rasterSE.getDataSource().newDataset(); |
192 |
BufferFactory bufferFactory = new BufferFactory(dsetCopy);
|
193 |
bufferFactory.setDrawableBands(drawableBands); |
194 |
|
195 |
if( interpolationMethod != BufferInterpolation.INTERPOLATION_Undefined &&
|
196 |
interpolationMethod != BufferInterpolation.INTERPOLATION_NearestNeighbour) { |
197 |
try {
|
198 |
if (RasterBuffer.isBufferTooBig(new double[] { dValues[0], dValues[3], dValues[2], dValues[1] }, drawableBands.length)) |
199 |
bufferFactory.setReadOnly(true);
|
200 |
|
201 |
bufferFactory.setAreaOfInterest(dValues[0], dValues[3], dValues[2] - dValues[0], dValues[1] - dValues[3]); |
202 |
} catch (InvalidSetViewException e) {
|
203 |
Logger.getLogger(this.getClass().getName()).debug("No se ha podido asignar la vista al inicial el proceso de recorte.", e); |
204 |
} |
205 |
buffer = bufferFactory.getRasterBuf(); |
206 |
|
207 |
insertLineLog(RasterToolsUtil.getText(this, "interpolando")); |
208 |
|
209 |
buffer = ((RasterBuffer) buffer).getAdjustedWindow(resolutionWidth, resolutionHeight, interpolationMethod); |
210 |
} else {
|
211 |
try {
|
212 |
if (RasterBuffer.isBufferTooBig(new double[] { 0, 0, resolutionWidth, resolutionHeight }, drawableBands.length)) |
213 |
bufferFactory.setReadOnly(true);
|
214 |
bufferFactory.setAreaOfInterest(dValues[0], dValues[3], Math.abs(dValues[2] - dValues[0]), Math.abs(dValues[1] - dValues[3]), resolutionWidth, resolutionHeight); |
215 |
buffer = bufferFactory.getRasterBuf(); |
216 |
} catch (InvalidSetViewException e) {
|
217 |
Logger.getLogger(this.getClass().getName()).debug("No se ha podido asignar la vista al inicial el proceso de recorte.", e); |
218 |
} |
219 |
} |
220 |
//TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
|
221 |
|
222 |
insertLineLog(RasterToolsUtil.getText(this, "salvando_imagen")); |
223 |
|
224 |
String finalFileName = ""; |
225 |
if (oneLayerPerBand) {
|
226 |
long[] milis = new long[drawableBands.length]; |
227 |
String[] fileNames = new String[drawableBands.length]; |
228 |
for (int i = 0; i < drawableBands.length; i++) { |
229 |
fileNames[i] = fileName + "_B" + drawableBands[i] + ".tif"; |
230 |
writerBufferServer.setBuffer(buffer, i); |
231 |
Params p = null;
|
232 |
if (params == null) |
233 |
p = GeoRasterWriter.getWriter(fileNames[i]).getParams(); |
234 |
else
|
235 |
p = params; |
236 |
grw = GeoRasterWriter.getWriter(writerBufferServer, fileNames[i], 1,
|
237 |
affineTransform, buffer.getWidth(), buffer.getHeight(), |
238 |
buffer.getDataType(), p, null);
|
239 |
grw.setColorBandsInterpretation(new String[]{DatasetColorInterpretation.GRAY_BAND}); |
240 |
grw.setWkt(dsetCopy.getWktProjection()); |
241 |
grw.dataWrite(); |
242 |
grw.writeClose(); |
243 |
saveToRmf(fileNames[i]); |
244 |
t2 = new java.util.Date().getTime();
|
245 |
milis[i] = (t2 - t1); |
246 |
t1 = new java.util.Date().getTime();
|
247 |
} |
248 |
if (incrementableTask != null) { |
249 |
incrementableTask.processFinalize(); |
250 |
incrementableTask = null;
|
251 |
} |
252 |
if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) { |
253 |
try {
|
254 |
for (int i = 0; i < drawableBands.length; i++) { |
255 |
RasterToolsUtil.loadLayer(viewName, fileNames[i], null);
|
256 |
} |
257 |
} catch (RasterNotLoadException e) {
|
258 |
RasterToolsUtil.messageBoxError("error_load_layer", this, e); |
259 |
} |
260 |
} |
261 |
for (int i = 0; i < drawableBands.length; i++) { |
262 |
if (externalActions != null) |
263 |
externalActions.end(new Object[] { fileName, new Long(milis[i]) }); |
264 |
} |
265 |
} else {
|
266 |
writerBufferServer.setBuffer(buffer, -1);
|
267 |
if (params == null) { |
268 |
finalFileName = fileName + ".tif";
|
269 |
params = GeoRasterWriter.getWriter(finalFileName).getParams(); |
270 |
} else
|
271 |
finalFileName = fileName; |
272 |
grw = GeoRasterWriter.getWriter(writerBufferServer, finalFileName, |
273 |
buffer.getBandCount(), affineTransform, buffer.getWidth(), |
274 |
buffer.getHeight(), buffer.getDataType(), params, null);
|
275 |
if(colorInterp != null) |
276 |
grw.setColorBandsInterpretation(colorInterp.getValues()); |
277 |
grw.setWkt(dsetCopy.getWktProjection()); |
278 |
grw.dataWrite(); |
279 |
grw.writeClose(); |
280 |
saveToRmf(finalFileName); |
281 |
t2 = new java.util.Date().getTime();
|
282 |
if (incrementableTask != null) { |
283 |
incrementableTask.processFinalize(); |
284 |
incrementableTask = null;
|
285 |
} |
286 |
//Damos tiempo a parar el Thread del incrementable para que no se cuelgue la ventana
|
287 |
//El tiempo es como m?nimo el de un bucle de del run de la tarea incrementable
|
288 |
Thread.sleep(600); |
289 |
cutFinalize(finalFileName, (t2 - t1)); |
290 |
} |
291 |
|
292 |
} catch (NotSupportedExtensionException e) {
|
293 |
Logger.getLogger(this.getClass().getName()).debug("No se ha podido obtener el writer. Extensi?n no soportada", e); |
294 |
} catch (RasterDriverException e) {
|
295 |
Logger.getLogger(this.getClass().getName()).debug("No se ha podido obtener el writer.", e); |
296 |
} catch (IOException e) { |
297 |
Logger.getLogger(this.getClass().getName()).debug("Error en la escritura en GeoRasterWriter.", e); |
298 |
} finally {
|
299 |
if (dsetCopy != null) |
300 |
dsetCopy.close(); |
301 |
buffer = null;
|
302 |
} |
303 |
} |
304 |
|
305 |
/**
|
306 |
* Acciones que se realizan al finalizar de crear los recortes de imagen.
|
307 |
* Este m?todo es llamado por el thread TailRasterProcess al finalizar.
|
308 |
*/
|
309 |
private void cutFinalize(String fileName, long milis) { |
310 |
if (!new File(fileName).exists()) |
311 |
return;
|
312 |
|
313 |
if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) { |
314 |
try {
|
315 |
RasterToolsUtil.loadLayer(viewName, fileName, null);
|
316 |
} catch (RasterNotLoadException e) {
|
317 |
RasterToolsUtil.messageBoxError("error_load_layer", this, e); |
318 |
} |
319 |
} |
320 |
|
321 |
if (externalActions != null) |
322 |
externalActions.end(new Object[]{fileName, new Long(milis)}); |
323 |
} |
324 |
|
325 |
/*
|
326 |
* (non-Javadoc)
|
327 |
* @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
|
328 |
*/
|
329 |
public int getPercent() { |
330 |
return (writerBufferServer != null) ? writerBufferServer.getPercent() : 0; |
331 |
} |
332 |
|
333 |
/*
|
334 |
* (non-Javadoc)
|
335 |
* @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
|
336 |
*/
|
337 |
public String getTitle() { |
338 |
return RasterToolsUtil.getText(this, "incremento_recorte"); |
339 |
} |
340 |
} |