Revision 13130 trunk/libraries/libCresques/src/org/cresques/io/EcwFile.java

View differences:

EcwFile.java
71 71
 * @author "Luis W. Sevilla" <sevilla_lui@gva.es>
72 72
 */
73 73
public class EcwFile extends GeoRasterFile implements JNCSProgressiveUpdate {
74
    //Lleva la cuenta del n?mero de actualizaciones que se hace de una imagen que corresponde con el 
75
    //n?mero de bandas que tiene. Esto es necesario ya que si una imagen tiene el mustResize a
76
    //true solo debe llamar a la funci?n resizeImage al actualizar la ?ltima banda, sino al hacer
77
    //un zoom menor que 1:1 se veria mal
78
    private static int nUpdate = 0;
79
    private JNCSFile file = null;
80
    private boolean bErrorOnOpen = false;
81
    private String errorMessage = null;
82
    private boolean multifile = false;
83
    private Extent v = null;
84
   
74
		//Lleva la cuenta del n?mero de actualizaciones que se hace de una imagen que corresponde con el
75
		//n?mero de bandas que tiene. Esto es necesario ya que si una imagen tiene el mustResize a
76
		//true solo debe llamar a la funci?n resizeImage al actualizar la ?ltima banda, sino al hacer
77
		//un zoom menor que 1:1 se veria mal
78
		private static int nUpdate = 0;
79
		private JNCSFile file = null;
80
		private String errorMessage = null;
81
		private boolean multifile = false;
82
		private Extent v = null;
85 83

  
86
    // Ultimo porcentaje de refresco. Se carga en el update y se
87
    // actualiza en el refreshUpdate
88
    private int lastRefreshPercent = 0;
89 84

  
90
    public EcwFile(IProjection proj, String fName) {
91
        super(proj, null);
92
        fName = DataSource.normalize(fName);
93
        super.setName(fName);
94
        extent = new Extent();
85
		// Ultimo porcentaje de refresco. Se carga en el update y se
86
		// actualiza en el refreshUpdate
87
		private int lastRefreshPercent = 0;
95 88

  
96
        try {
97
        	
98
        	if (!new File(fName).exists() && !fName.startsWith("ecwp:")){
99
        		System.err.println("No se puede abrir el archivo");
100
        		return;
101
        	}
102
        	
103
            file = new JNCSFile(fName, false);
104
        	load();
105
            //readGeoInfo(fName);
106
            bandCount = file.numBands;
89
		public EcwFile(IProjection proj, String fName) {
90
				super(proj, null);
91
				fName = DataSource.normalize(fName);
92
				super.setName(fName);
93
				extent = new Extent();
107 94

  
108
            if ( bandCount > 2) {
109
                    setBand(RED_BAND,   0);
110
                    setBand(GREEN_BAND, 1);
111
                    setBand(BLUE_BAND,  2);
112
            } else
113
                    setBand(RED_BAND|GREEN_BAND|BLUE_BAND, 0);
114
        } catch (Exception e) {
115
            bErrorOnOpen = true;
116
            errorMessage = e.getMessage();
117
            System.err.println(errorMessage);
118
            e.printStackTrace();
119
        }
120
    }
95
				try {
121 96

  
122
    /**
123
     * Carga un ECW.
124
     *
125
     * @param fname
126
     */
127
    public GeoFile load() {
128
        double minX;
129
        double minY;
130
        double maxX;
131
        double maxY;
97
					if (!new File(fName).exists() && !fName.startsWith("ecwp:")){
98
						System.err.println("No se puede abrir el archivo");
99
						return;
100
					}
132 101

  
133
        if(file.cellIncrementY > 0)
134
        	file.cellIncrementY = -file.cellIncrementY;
135
        
136
        minX = file.originX;
137
        maxY = file.originY;
138
        maxX = file.originX +
139
               ((double) (file.width - 1) * file.cellIncrementX);
140
        minY = file.originY +
141
               ((double) (file.height - 1) * file.cellIncrementY);
142
        
143
        extent = new Extent(minX, minY, maxX, maxY);
144
        requestExtent = extent;
145
        return this;
146
    }
102
						file = new JNCSFile(fName, false);
103
					load();
104
						//readGeoInfo(fName);
105
						bandCount = file.numBands;
147 106

  
148
    public void close() {
149
    	if(file != null){
150
    		file.close(true);
151
    		file = null;
152
    	}
153
    }
107
						if ( bandCount > 2) {
108
										setBand(RED_BAND,   0);
109
										setBand(GREEN_BAND, 1);
110
										setBand(BLUE_BAND,  2);
111
						} else
112
										setBand(RED_BAND|GREEN_BAND|BLUE_BAND, 0);
113
				} catch (Exception e) {
114
						errorMessage = e.getMessage();
115
						System.err.println(errorMessage);
116
						e.printStackTrace();
117
				}
118
		}
154 119

  
155
    /**
156
     * Devuelve el ancho de la imagen
157
     */
158
    public int getWidth() {
159
        return file.width;
160
    }
120
		/**
121
		 * Carga un ECW.
122
		 *
123
		 * @param fname
124
		 */
125
		public GeoFile load() {
126
				double minX;
127
				double minY;
128
				double maxX;
129
				double maxY;
161 130

  
162
    /**
163
     * Devuelve el alto de la imagen
164
     */
165
    public int getHeight() {
166
        return file.height;
167
    }
131
				if(file.cellIncrementY > 0)
132
					file.cellIncrementY = -file.cellIncrementY;
168 133

  
169
    /**
170
     *
171
     */
172
    public void setMultifile(boolean mult) {
173
        this.multifile = mult;
174
    }
134
				minX = file.originX;
135
				maxY = file.originY;
136
				maxX = file.originX +
137
							 ((double) (file.width - 1) * file.cellIncrementX);
138
				minY = file.originY +
139
							 ((double) (file.height - 1) * file.cellIncrementY);
175 140

  
176
    public void setView(Extent e) {
177
    	//Aplicamos la transformaci?n a la vista en caso de que haya un fichero .rmf 
178
    	/*    	         
179
    	if(file.cellIncrementY > 0)
180
        	file.cellIncrementY = -file.cellIncrementY;
181
    	if(minX < file.originX)
182
    		minX = file.originX;
183
    	if(maxY > file.originY)
184
    		maxY = file.originY;
185
    	if(maxX > (file.originX + ((double) (file.width - 1) * file.cellIncrementX)))
186
    		maxX = file.originX + ((double) (file.width - 1) * file.cellIncrementX);
187
    	if(minY < file.originY + ((double) (file.height - 1) * file.cellIncrementY))
188
    		minY = file.originY + ((double) (file.height - 1) * file.cellIncrementY);
189
    	
141
				extent = new Extent(minX, minY, maxX, maxY);
142
				requestExtent = extent;
143
				return this;
144
		}
145

  
146
		public void close() {
147
			if(file != null){
148
				file.close(true);
149
				file = null;
150
			}
151
		}
152

  
153
		/**
154
		 * Devuelve el ancho de la imagen
155
		 */
156
		public int getWidth() {
157
				return file.width;
158
		}
159

  
160
		/**
161
		 * Devuelve el alto de la imagen
162
		 */
163
		public int getHeight() {
164
				return file.height;
165
		}
166

  
167
		/**
168
		 *
169
		 */
170
		public void setMultifile(boolean mult) {
171
				this.multifile = mult;
172
		}
173

  
174
		public void setView(Extent e) {
175
			//Aplicamos la transformaci?n a la vista en caso de que haya un fichero .rmf
176
			/*
177
			if(file.cellIncrementY > 0)
178
					file.cellIncrementY = -file.cellIncrementY;
179
			if(minX < file.originX)
180
				minX = file.originX;
181
			if(maxY > file.originY)
182
				maxY = file.originY;
183
			if(maxX > (file.originX + ((double) (file.width - 1) * file.cellIncrementX)))
184
				maxX = file.originX + ((double) (file.width - 1) * file.cellIncrementX);
185
			if(minY < file.originY + ((double) (file.height - 1) * file.cellIncrementY))
186
				minY = file.originY + ((double) (file.height - 1) * file.cellIncrementY);
187

  
190 188
		Extent transformView = new Extent(	minX, minY, maxX, maxY );*/
191
        v = new Extent(e);
192
    }
189
				v = new Extent(e);
190
		}
193 191

  
194
    public Extent getView() {
195
        return v;
196
    }
197
    
198
    private void setFileView(int numBands, int [] bandList, ChunkFrame f)
199
    	throws JNCSFileNotOpenException, JNCSInvalidSetViewException {
200
        file.setView(file.numBands, bandList, f.v.minX(), f.v.maxY(), f.v.maxX(), f.v.minY(), f.width, f.height);
201
    }
192
		public Extent getView() {
193
				return v;
194
		}
202 195

  
203
    /**
204
     * Obtiene un trozo de imagen (determinado por la vista y los par?metros.
205
     *
206
     * @param width
207
     * @param height
208
     */
209
    public synchronized Image updateImage(int width, int height, ICoordTrans rp) {
210
        // TODO reproyectar para devolver el trozo de imagen pedida sobre ...
211
        // la proyecci?n de destino.
212
        int line = 0;
213
        boolean mustResize = false;
214
        Dimension fullSize = null;
215
        Image ecwImage = null;
196
		private void setFileView(int numBands, int [] bandList, ChunkFrame f)
197
			throws JNCSFileNotOpenException, JNCSInvalidSetViewException {
198
				file.setView(file.numBands, bandList, f.v.minX(), f.v.maxY(), f.v.maxX(), f.v.minY(), f.width, f.height);
199
		}
216 200

  
217
        if (file == null) {
218
            return ecwImage;
219
        }
201
		/**
202
		 * Obtiene un trozo de imagen (determinado por la vista y los par?metros.
203
		 *
204
		 * @param width
205
		 * @param height
206
		 */
207
		public synchronized Image updateImage(int width, int height, ICoordTrans rp) {
208
				// TODO reproyectar para devolver el trozo de imagen pedida sobre ...
209
				// la proyecci?n de destino.
210
				int line = 0;
211
				Dimension fullSize = null;
212
				Image ecwImage = null;
220 213

  
221
        try {
222
            int[] bandlist;
223
            int[] bandListTriband;
224
            int[] pRGBArray = null;
214
				if (file == null) {
215
						return ecwImage;
216
				}
225 217

  
226
            if(mustVerifySize()){
227
            // Work out the correct aspect for the setView call.
228
	            double dFileAspect = (double) v.width() / (double) v.height();
229
	            double dWindowAspect = (double) width / (double) height;
230
	
231
	            if (dFileAspect > dWindowAspect) {
232
	                height = (int) ((double) width / dFileAspect);
233
	            } else {
234
	                width = (int) ((double) height * dFileAspect);
235
	            }
236
            }
237
            fullSize = new Dimension(width, height);
218
				try {
219
						int[] bandlist;
220
						int[] bandListTriband;
221
						int[] pRGBArray = null;
238 222

  
239
            //System.out.println("fullSize = ("+width+","+height+")");
240
            // Peta en los peque?os ... arreglar antes de meter del todo
241
            ChunkFrame[] frames = ChunkFrame.computeFrames(file, v, fullSize, extent);
223
						if(mustVerifySize()){
224
						// Work out the correct aspect for the setView call.
225
							double dFileAspect = (double) v.width() / (double) v.height();
226
							double dWindowAspect = (double) width / (double) height;
242 227

  
243
            if (frames.length == 1) {
244
                width = frames[0].width;
245
                height = frames[0].height;
228
							if (dFileAspect > dWindowAspect) {
229
									height = (int) ((double) width / dFileAspect);
230
							} else {
231
									width = (int) ((double) height * dFileAspect);
232
							}
233
						}
234
						fullSize = new Dimension(width, height);
246 235

  
247
                if (width <= 0) {
248
                    width = 1;
249
                }
236
						//System.out.println("fullSize = ("+width+","+height+")");
237
						// Peta en los peque?os ... arreglar antes de meter del todo
238
						ChunkFrame[] frames = ChunkFrame.computeFrames(file, v, fullSize, extent);
250 239

  
251
                if (height <= 0) {
252
                    height = 1;
253
                }
254
            }
240
						if (frames.length == 1) {
241
								width = frames[0].width;
242
								height = frames[0].height;
255 243

  
256
            /*                        JNCSDatasetPoint ptMin = file.convertWorldToDataset(v.minX(), v.minY());
257
                                    JNCSDatasetPoint ptMax = file.convertWorldToDataset(v.maxX(), v.maxY());
258
                                    System.out.println("Dataset coords Width = "+(ptMax.x-ptMin.x)+", px width ="+width);
259
                                    // BEGIN Cambiando para soportar e < 1:1
260
                                    // TODO Mejorarlo para que los PAN con un zoom muy grande sean correctos
261
                                    if ((ptMax.x-ptMin.x)<width) {
262
                                            width = ptMax.x-ptMin.x;
263
                                            height = ptMin.y-ptMax.y;
264
                                            System.out.println("Size=("+width+","+height+")");
265
                                            mustResize = true;
266
                                    }*/
244
								if (width <= 0) {
245
										width = 1;
246
								}
267 247

  
268
            // Create an image of the ecw file.
269
            if (doTransparency) {
270
                ecwImage = new BufferedImage(width, height,
271
                                             BufferedImage.TYPE_INT_ARGB);
272
            } else {
273
                ecwImage = new BufferedImage(width, height,
274
                                             BufferedImage.TYPE_INT_RGB);
275
            }
248
								if (height <= 0) {
249
										height = 1;
250
								}
251
						}
276 252

  
277
            pRGBArray = new int[width];
253
						/*                        JNCSDatasetPoint ptMin = file.convertWorldToDataset(v.minX(), v.minY());
254
																		JNCSDatasetPoint ptMax = file.convertWorldToDataset(v.maxX(), v.maxY());
255
																		System.out.println("Dataset coords Width = "+(ptMax.x-ptMin.x)+", px width ="+width);
256
																		// BEGIN Cambiando para soportar e < 1:1
257
																		// TODO Mejorarlo para que los PAN con un zoom muy grande sean correctos
258
																		if ((ptMax.x-ptMin.x)<width) {
259
																						width = ptMax.x-ptMin.x;
260
																						height = ptMin.y-ptMax.y;
261
																						System.out.println("Size=("+width+","+height+")");
262
																						mustResize = true;
263
																		}*/
278 264

  
279
            // Setup the view parameters for the ecw file.
280
            bandlist = new int[bandCount];
281
            bandListTriband = new int[bandCount];
265
						// Create an image of the ecw file.
266
						if (doTransparency) {
267
								ecwImage = new BufferedImage(width, height,
268
																						 BufferedImage.TYPE_INT_ARGB);
269
						} else {
270
								ecwImage = new BufferedImage(width, height,
271
																						 BufferedImage.TYPE_INT_RGB);
272
						}
282 273

  
283
            if (bandCount > 2) {
284
                bandlist[0] = getBand(RED_BAND);
285
                bandlist[1] = getBand(GREEN_BAND);
286
                bandlist[2] = getBand(BLUE_BAND);
274
						pRGBArray = new int[width];
287 275

  
288
                if (bandCount > 3) {
289
                    for (int i = 3; i < bandCount; i++) {
290
                        bandlist[i] = 0;
291
                    }
292
                }
293
            } else {
294
                for (int i = 0; i < bandCount; i++) {
295
                    bandlist[i] = i;
296
                }
297
            }
276
						// Setup the view parameters for the ecw file.
277
						bandlist = new int[bandCount];
278
						bandListTriband = new int[bandCount];
298 279

  
299
            if (bandCount == 3) {
300
                bandListTriband[0] = 0;
301
                bandListTriband[1] = 1;
302
                bandListTriband[2] = 2;
303
            }
280
						if (bandCount > 2) {
281
								bandlist[0] = getBand(RED_BAND);
282
								bandlist[1] = getBand(GREEN_BAND);
283
								bandlist[2] = getBand(BLUE_BAND);
304 284

  
305
            for (int nChunk = 0; nChunk < frames.length; nChunk++) {
306
                ChunkFrame f = frames[nChunk];
285
								if (bandCount > 3) {
286
										for (int i = 3; i < bandCount; i++) {
287
												bandlist[i] = 0;
288
										}
289
								}
290
						} else {
291
								for (int i = 0; i < bandCount; i++) {
292
										bandlist[i] = i;
293
								}
294
						}
307 295

  
308
                // Set the view			
309
                if (bandCount != 3) {
310
                    setFileView(file.numBands, bandlist, f);
311
                } else {
312
                    setFileView(file.numBands, bandListTriband, f);
313
                }
296
						if (bandCount == 3) {
297
								bandListTriband[0] = 0;
298
								bandListTriband[1] = 1;
299
								bandListTriband[2] = 2;
300
						}
314 301

  
315
                /* 
316
                 * Esta peli es porque el Ecw no intercambia las bandas con lo que me toca hacerlo
317
                 * a mano. Primero detectamos si se ha alterado el orden de las mismas. Si es as?
318
                 * calculamos mascaras y desplazamientos y hacemos una copia en pRGBArrayCopy
319
                 * con las bandas alteradas de orden
320
                 */
321
                int[] pRGBArrayCopy = null;
322
                int[] mascara = new int[3];
323
                int[] shl = new int[3];
324
                int[] shr = new int[3];
325
                boolean order = true;
302
						for (int nChunk = 0; nChunk < frames.length; nChunk++) {
303
								ChunkFrame f = frames[nChunk];
326 304

  
327
                if (bandCount == 3) {
328
                    for (int i = 0; i < bandCount; i++)
329
                        if (bandlist[i] != i) {
330
                            order = false;
331
                        }
305
								// Set the view
306
								if (bandCount != 3) {
307
										setFileView(file.numBands, bandlist, f);
308
								} else {
309
										setFileView(file.numBands, bandListTriband, f);
310
								}
332 311

  
333
                    if (!order) {
334
                        for (int i = 0; i < bandCount; i++) {
335
                            switch (bandlist[i]) {
336
                            case 0:
337
                                mascara[i] = 0x00ff0000;
338
                                break;
339
                            case 1:
340
                                mascara[i] = 0x0000ff00;
341
                                break;
342
                            case 2:
343
                                mascara[i] = 0x000000ff;
344
                                break;
345
                            }
346
                            if ((i == 1) && (bandlist[i] == 0)) 
347
                                shr[i] = 8;
348
                            if ((i == 2) && (bandlist[i] == 0)) 
349
                                shr[i] = 16;
350
                            if ((i == 0) && (bandlist[i] == 1)) 
351
                                shl[i] = 8;
352
                            if ((i == 2) && (bandlist[i] == 1))
353
                                shr[i] = 8;
354
                            if ((i == 0) && (bandlist[i] == 2)) 
355
                                shl[i] = 16;
356
                            if ((i == 1) && (bandlist[i] == 2))
357
                                shl[i] = 8;
358
                        }
359
                    }
360
                }
312
								/*
313
								 * Esta peli es porque el Ecw no intercambia las bandas con lo que me toca hacerlo
314
								 * a mano. Primero detectamos si se ha alterado el orden de las mismas. Si es as?
315
								 * calculamos mascaras y desplazamientos y hacemos una copia en pRGBArrayCopy
316
								 * con las bandas alteradas de orden
317
								 */
318
								int[] pRGBArrayCopy = null;
319
								int[] mascara = new int[3];
320
								int[] shl = new int[3];
321
								int[] shr = new int[3];
322
								boolean order = true;
361 323

  
362
                // Read the scan lines
363
                for (line = 0; line < f.height; line++) {
364
                    file.readLineRGBA(pRGBArray);
324
								if (bandCount == 3) {
325
										for (int i = 0; i < bandCount; i++)
326
												if (bandlist[i] != i) {
327
														order = false;
328
												}
365 329

  
366
                    if ((bandCount == 3) && !order) {
367
                        pRGBArrayCopy = new int[pRGBArray.length];
330
										if (!order) {
331
												for (int i = 0; i < bandCount; i++) {
332
														switch (bandlist[i]) {
333
														case 0:
334
																mascara[i] = 0x00ff0000;
335
																break;
336
														case 1:
337
																mascara[i] = 0x0000ff00;
338
																break;
339
														case 2:
340
																mascara[i] = 0x000000ff;
341
																break;
342
														}
343
														if ((i == 1) && (bandlist[i] == 0))
344
																shr[i] = 8;
345
														if ((i == 2) && (bandlist[i] == 0))
346
																shr[i] = 16;
347
														if ((i == 0) && (bandlist[i] == 1))
348
																shl[i] = 8;
349
														if ((i == 2) && (bandlist[i] == 1))
350
																shr[i] = 8;
351
														if ((i == 0) && (bandlist[i] == 2))
352
																shl[i] = 16;
353
														if ((i == 1) && (bandlist[i] == 2))
354
																shl[i] = 8;
355
												}
356
										}
357
								}
368 358

  
369
                        for (int i = 0; i < pRGBArray.length; i++) {
370
                            pRGBArrayCopy[i] = (pRGBArray[i] & 0xff000000) +
371
                                               (((pRGBArray[i] & mascara[2]) << shl[2]) >> shr[2]) +
372
                                               (((pRGBArray[i] & mascara[1]) << shl[1]) >> shr[1]) +
373
                                               (((pRGBArray[i] & mascara[0]) << shl[0]) >> shr[0]);
374
                        }
359
								// Read the scan lines
360
								for (line = 0; line < f.height; line++) {
361
										file.readLineRGBA(pRGBArray);
375 362

  
376
                        pRGBArray = pRGBArrayCopy;
377
                    }
363
										if ((bandCount == 3) && !order) {
364
												pRGBArrayCopy = new int[pRGBArray.length];
378 365

  
379
                    // Prueba de sustituci?n de color transparente
380
                    if (doTransparency) {
381
                        if (line == 0) {
382
                            tFilter.debug = true;
383
                        }
366
												for (int i = 0; i < pRGBArray.length; i++) {
367
														pRGBArrayCopy[i] = (pRGBArray[i] & 0xff000000) +
368
																							 (((pRGBArray[i] & mascara[2]) << shl[2]) >> shr[2]) +
369
																							 (((pRGBArray[i] & mascara[1]) << shl[1]) >> shr[1]) +
370
																							 (((pRGBArray[i] & mascara[0]) << shl[0]) >> shr[0]);
371
												}
384 372

  
385
                        tFilter.filterLine(pRGBArray);
386
                        tFilter.debug = false;
387
                    }
373
												pRGBArray = pRGBArrayCopy;
374
										}
388 375

  
389
                    ((BufferedImage) ecwImage).setRGB(f.pos.x, f.pos.y + line,
390
                                                      f.width, 1, pRGBArray, 0,
391
                                                      f.width);
392
                }
393
            }
376
										// Prueba de sustituci?n de color transparente
377
										if (doTransparency) {
378
												if (line == 0) {
379
														tFilter.debug = true;
380
												}
394 381

  
395
            if (frames[0].mustResize) {
396
                //System.out.println("resize "+fullSize);
397
                return resizeImage(fullSize, ecwImage);
398
            }
382
												tFilter.filterLine(pRGBArray);
383
												tFilter.debug = false;
384
										}
399 385

  
400
            /*
401
             * La excepci?n atrapada es la de 'zoom > 1:1 no valido'
402
            } catch (com.ermapper.ecw.JNCSInvalidSetViewException e) {
403
                    System.err.println(errorMessage);
404
                    e.printStackTrace(); */
405
        } catch (com.ermapper.ecw.JNCSException e) { //java.lang.ArrayIndexOutOfBoundsException:
406
            bErrorOnOpen = true;
407
            System.err.println("EcwFile JNCS Error en la l?nea " + line + "/" +
408
                               height);
409
            System.err.println(e.getMessage());
410
            e.printStackTrace();
411
        } catch (java.lang.ArrayIndexOutOfBoundsException e) { //:
412
            bErrorOnOpen = true;
413
            System.err.println("EcwFile ArrayIndex Error en la l?nea " + line +
414
                               "/" + height);
415
            System.err.println(e.getMessage());
416
            e.printStackTrace();
417
        } catch (Exception e) {
418
            bErrorOnOpen = true;
419
            errorMessage = e.getMessage();
386
										((BufferedImage) ecwImage).setRGB(f.pos.x, f.pos.y + line,
387
																											f.width, 1, pRGBArray, 0,
388
																											f.width);
389
								}
390
						}
420 391

  
421
            //			g.drawString(errorMessage, 0, 50);
422
            System.err.println(errorMessage);
423
            e.printStackTrace();
424
        }
392
						if (frames[0].mustResize) {
393
								//System.out.println("resize "+fullSize);
394
								return resizeImage(fullSize, ecwImage);
395
						}
425 396

  
426
        lastRefreshPercent = file.getPercentComplete();
427
        System.out.println("Leido al " + lastRefreshPercent + " %.");
397
						/*
398
						 * La excepci?n atrapada es la de 'zoom > 1:1 no valido'
399
						} catch (com.ermapper.ecw.JNCSInvalidSetViewException e) {
400
										System.err.println(errorMessage);
401
										e.printStackTrace(); */
402
				} catch (com.ermapper.ecw.JNCSException e) { //java.lang.ArrayIndexOutOfBoundsException:
403
						System.err.println("EcwFile JNCS Error en la l?nea " + line + "/" +
404
															 height);
405
						System.err.println(e.getMessage());
406
						e.printStackTrace();
407
				} catch (java.lang.ArrayIndexOutOfBoundsException e) { //:
408
						System.err.println("EcwFile ArrayIndex Error en la l?nea " + line +
409
															 "/" + height);
410
						System.err.println(e.getMessage());
411
						e.printStackTrace();
412
				} catch (Exception e) {
413
						errorMessage = e.getMessage();
428 414

  
429
        return ecwImage;
430
    }
415
						//			g.drawString(errorMessage, 0, 50);
416
						System.err.println(errorMessage);
417
						e.printStackTrace();
418
				}
431 419

  
432
    /**
433
     * Redimensionado de imagen
434
     * La funci?n getScaledInstance nos devuelve un tipo image que no sirve por lo que
435
     * habr? que crear  buffImg como BufferedImage y copiar los datos devueltos por esta
436
     * funci?n a este que es el que ser? devuelto por la funci?n
437
     * @param sz
438
     * @param image        Image de entrada
439
     * @return        Imagen reescalada
440
     */
441
    private Image resizeImage(Dimension sz, Image image) {
442
        Image buffImg = null;
443
        Image img = image.getScaledInstance((int) sz.getWidth(),
444
                                            (int) sz.getHeight(),
445
                                            Image.SCALE_SMOOTH);
420
				lastRefreshPercent = file.getPercentComplete();
421
				System.out.println("Leido al " + lastRefreshPercent + " %.");
446 422

  
447
        //Todo este pollo es para copiar el tipo image devuelto a BufferedImage
448
        buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null),
449
                                    BufferedImage.TYPE_INT_ARGB);
423
				return ecwImage;
424
		}
450 425

  
451
        int[] pixels = new int[img.getWidth(null) * img.getHeight(null)];
452
        PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(null),
453
                                           img.getHeight(null), pixels, 0,
454
                                           img.getWidth(null));
426
		/**
427
		 * Redimensionado de imagen
428
		 * La funci?n getScaledInstance nos devuelve un tipo image que no sirve por lo que
429
		 * habr? que crear  buffImg como BufferedImage y copiar los datos devueltos por esta
430
		 * funci?n a este que es el que ser? devuelto por la funci?n
431
		 * @param sz
432
		 * @param image        Image de entrada
433
		 * @return        Imagen reescalada
434
		 */
435
		private Image resizeImage(Dimension sz, Image image) {
436
				Image buffImg = null;
437
				Image img = image.getScaledInstance((int) sz.getWidth(),
438
																						(int) sz.getHeight(),
439
																						Image.SCALE_SMOOTH);
455 440

  
456
        try {
457
            pg.grabPixels();
458
        } catch (InterruptedException e) {
459
            e.printStackTrace();
460
        }
441
				//Todo este pollo es para copiar el tipo image devuelto a BufferedImage
442
				buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null),
443
																		BufferedImage.TYPE_INT_ARGB);
461 444

  
462
        for (int j = 0; j < buffImg.getHeight(null); j++) {
463
            for (int i = 0; i < buffImg.getWidth(null); i++) {
464
                ((BufferedImage) buffImg).setRGB(i, j,
465
                                                 pixels[(j * buffImg.getWidth(null)) +
466
                                                 i]);
467
            }
468
        }
445
				int[] pixels = new int[img.getWidth(null) * img.getHeight(null)];
446
				PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(null),
447
																					 img.getHeight(null), pixels, 0,
448
																					 img.getWidth(null));
469 449

  
470
        return buffImg;
471
    }
450
				try {
451
						pg.grabPixels();
452
				} catch (InterruptedException e) {
453
						e.printStackTrace();
454
				}
472 455

  
473
    /**
474
     * Reproyecta el raster.
475
     */
476
    public void reProject(ICoordTrans rp) {
477
        // TODO metodo reProject pendiente de implementar
478
    }
456
				for (int j = 0; j < buffImg.getHeight(null); j++) {
457
						for (int i = 0; i < buffImg.getWidth(null); i++) {
458
								((BufferedImage) buffImg).setRGB(i, j,
459
																								 pixels[(j * buffImg.getWidth(null)) +
460
																								 i]);
461
						}
462
				}
479 463

  
480
    /**
481
     * Soporte para actualizaci?n de la imagen
482
     * @see com.ermapper.ecw.JNCSProgressiveUpdate#refreshUpdate(int, int, double, double, double, double)
483
     */
484
    public void refreshUpdate(int nWidth, int nHeight, double dWorldTLX,
485
                              double dWorldTLY, double dWorldBRX,
486
                              double dWorldBRY) {
487
        int completado = file.getPercentComplete();
488
        System.out.println("EcwFile: se actualiza 1: " + completado +
489
                           " % completado");
464
				return buffImg;
465
		}
490 466

  
491
        if ((updatable != null) && (lastRefreshPercent < 100)) {
492
            if (((completado - lastRefreshPercent) > 25) ||
493
                    (completado == 100)) {
494
                lastRefreshPercent = file.getPercentComplete();
495
                updatable.repaint();
496
            }
497
        }
498
    }
467
		/**
468
		 * Reproyecta el raster.
469
		 */
470
		public void reProject(ICoordTrans rp) {
471
				// TODO metodo reProject pendiente de implementar
472
		}
499 473

  
500
    public void refreshUpdate(int nWidth, int nHeight, int dDatasetTLX,
501
                              int dDatasetTLY, int dDatasetBRX, int dDatasetBRY) {
502
        System.out.println("EcwFile: se actualiza 2");
503
    }
474
		/**
475
		 * Soporte para actualizaci?n de la imagen
476
		 * @see com.ermapper.ecw.JNCSProgressiveUpdate#refreshUpdate(int, int, double, double, double, double)
477
		 */
478
		public void refreshUpdate(int nWidth, int nHeight, double dWorldTLX,
479
															double dWorldTLY, double dWorldBRX,
480
															double dWorldBRY) {
481
				int completado = file.getPercentComplete();
482
				System.out.println("EcwFile: se actualiza 1: " + completado +
483
													 " % completado");
504 484

  
505
    /**
506
     *  Esta funci?n es porque el Ecw no intercambia las bandas con lo que me toca hacerlo
507
     * a mano. Primero detectamos si se ha alterado el orden de las mismas. Si es as?
508
     * calculamos mascaras y desplazamientos y hacemos una copia en pRGBArrayCopy
509
     * con las bandas alteradas de orden
510
     * @param bandList        lista de bandas
511
     * @param mask mascara
512
     * @param shl desplazamiento izquierda
513
     * @param shr desplazamiento derecha
514
     */
515
    private boolean calcMaskAndShift(int[] bandList, int[] mask, int[] shl,
516
                                     int[] shr) {
517
        boolean order = true;
485
				if ((updatable != null) && (lastRefreshPercent < 100)) {
486
						if (((completado - lastRefreshPercent) > 25) ||
487
										(completado == 100)) {
488
								lastRefreshPercent = file.getPercentComplete();
489
								updatable.repaint();
490
						}
491
				}
492
		}
518 493

  
519
        if (bandCount == 3) {
520
            for (int i = 0; i < bandCount; i++)
521
                if (bandList[i] != i) {
522
                    order = false;
523
                }
494
		public void refreshUpdate(int nWidth, int nHeight, int dDatasetTLX,
495
															int dDatasetTLY, int dDatasetBRX, int dDatasetBRY) {
496
				System.out.println("EcwFile: se actualiza 2");
497
		}
524 498

  
525
            if (!order) {
526
                for (int i = 0; i < bandCount; i++) {
527
                    switch (bandList[i]) {
528
                    case 0:
529
                        mask[i] = 0x00ff0000;
530
                        break;
531
                    case 1:
532
                        mask[i] = 0x0000ff00;
533
                        break;
534
                    case 2:
535
                        mask[i] = 0x000000ff;
536
                        break;
537
                    }
538
                    
539
                    if ((i == 1) && (bandList[i] == 0))
540
                        shr[i] = 8;
541
                    if ((i == 2) && (bandList[i] == 0)) 
542
                        shr[i] = 16;
543
                    if ((i == 0) && (bandList[i] == 1))
544
                        shl[i] = 8;
545
                    if ((i == 2) && (bandList[i] == 1))
546
                        shr[i] = 8;
547
                    if ((i == 0) && (bandList[i] == 2))
548
                        shl[i] = 16;
549
                    if ((i == 1) && (bandList[i] == 2))
550
                        shl[i] = 8;
551
                }
552
            }
553
        }
499
		/**
500
		 *  Esta funci?n es porque el Ecw no intercambia las bandas con lo que me toca hacerlo
501
		 * a mano. Primero detectamos si se ha alterado el orden de las mismas. Si es as?
502
		 * calculamos mascaras y desplazamientos y hacemos una copia en pRGBArrayCopy
503
		 * con las bandas alteradas de orden
504
		 * @param bandList        lista de bandas
505
		 * @param mask mascara
506
		 * @param shl desplazamiento izquierda
507
		 * @param shr desplazamiento derecha
508
		 */
509
		private boolean calcMaskAndShift(int[] bandList, int[] mask, int[] shl,
510
																		 int[] shr) {
511
				boolean order = true;
554 512

  
555
        return order;
556
    }
513
				if (bandCount == 3) {
514
						for (int i = 0; i < bandCount; i++)
515
								if (bandList[i] != i) {
516
										order = false;
517
								}
557 518

  
558
    /**
559
     * Intercambio de bandas para ecw manual. Se le pasa el array de bytes que se desea intercambiar
560
     * la mascara y desplazamientos previamente calculados con calcMaskAndShift
561
     * @param order        true si el orden de las bandas no est? alterado y false si lo est?
562
     * @param pRGBArray array de
563
     * @param mascara
564
     * @param shl desplazamiento a izquierda
565
     * @param shr desplazamiento a derecha
566
     * @return array con las bandas cambiadas
567
     */
568
    private int[] changeBands(boolean order, int[] pRGBArray, int[] mascara,
569
                              int[] shl, int[] shr) {
570
        if ((bandCount == 3) && !order) {
571
            int[] pRGBArrayCopy = new int[pRGBArray.length];
519
						if (!order) {
520
								for (int i = 0; i < bandCount; i++) {
521
										switch (bandList[i]) {
522
										case 0:
523
												mask[i] = 0x00ff0000;
524
												break;
525
										case 1:
526
												mask[i] = 0x0000ff00;
527
												break;
528
										case 2:
529
												mask[i] = 0x000000ff;
530
												break;
531
										}
572 532

  
573
            for (int i = 0; i < pRGBArray.length; i++) {
574
                pRGBArrayCopy[i] = (pRGBArray[i] & 0xff000000) +
575
                                   (((pRGBArray[i] & mascara[2]) << shl[2]) >> shr[2]) +
576
                                   (((pRGBArray[i] & mascara[1]) << shl[1]) >> shr[1]) +
577
                                   (((pRGBArray[i] & mascara[0]) << shl[0]) >> shr[0]);
578
            }
533
										if ((i == 1) && (bandList[i] == 0))
534
												shr[i] = 8;
535
										if ((i == 2) && (bandList[i] == 0))
536
												shr[i] = 16;
537
										if ((i == 0) && (bandList[i] == 1))
538
												shl[i] = 8;
539
										if ((i == 2) && (bandList[i] == 1))
540
												shr[i] = 8;
541
										if ((i == 0) && (bandList[i] == 2))
542
												shl[i] = 16;
543
										if ((i == 1) && (bandList[i] == 2))
544
												shl[i] = 8;
545
								}
546
						}
547
				}
579 548

  
580
            return pRGBArrayCopy;
581
        }
549
				return order;
550
		}
582 551

  
583
        return pRGBArray;
584
    }
552
		/**
553
		 * Intercambio de bandas para ecw manual. Se le pasa el array de bytes que se desea intercambiar
554
		 * la mascara y desplazamientos previamente calculados con calcMaskAndShift
555
		 * @param order        true si el orden de las bandas no est? alterado y false si lo est?
556
		 * @param pRGBArray array de
557
		 * @param mascara
558
		 * @param shl desplazamiento a izquierda
559
		 * @param shr desplazamiento a derecha
560
		 * @return array con las bandas cambiadas
561
		 */
562
		private int[] changeBands(boolean order, int[] pRGBArray, int[] mascara,
563
															int[] shl, int[] shr) {
564
				if ((bandCount == 3) && !order) {
565
						int[] pRGBArrayCopy = new int[pRGBArray.length];
585 566

  
586
    /**
587
     * Asigna al objeto Image los valores con los dato de la imagen contenidos en el
588
     * vector de enteros.
589
     * @param image        imagen con los datos actuales
590
     * @param startX        inicio de la posici?n en X dentro de la imagen
591
     * @param startY        inicio de la posici?n en X dentro de la imagen
592
     * @param w        Ancho de la imagen
593
     * @param h        Alto de la imagen
594
     * @param rgbArray        vector que contiene la banda que se va a sustituir
595
     * @param offset        desplazamiento
596
     * @param scansize        tama?o de imagen recorrida por cada p
597
     */
598
    protected void setRGBLine(BufferedImage image, int startX, int startY,
599
                              int w, int h, int[] rgbArray, int offset,
600
                              int scansize) {
601
        image.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
602
    }
567
						for (int i = 0; i < pRGBArray.length; i++) {
568
								pRGBArrayCopy[i] = (pRGBArray[i] & 0xff000000) +
569
																	 (((pRGBArray[i] & mascara[2]) << shl[2]) >> shr[2]) +
570
																	 (((pRGBArray[i] & mascara[1]) << shl[1]) >> shr[1]) +
571
																	 (((pRGBArray[i] & mascara[0]) << shl[0]) >> shr[0]);
572
						}
603 573

  
604
    /**
605
     * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
606
     * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
607
     * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
608
     * banda correspondiente a flags es sustituida por los datos del vector.
609
     * @param image        imagen con los datos actuales
610
     * @param startX        inicio de la posici?n en X dentro de la imagen
611
     * @param startY        inicio de la posici?n en X dentro de la imagen
612
     * @param w        Ancho de la imagen
613
     * @param h        Alto de la imagen
614
     * @param rgbArray        vector que contiene la banda que se va a sustituir
615
     * @param offset        desplazamiento
616
     * @param scansize        tama?o de imagen recorrida por cada paso
617
     * @param flags        banda que se va a sustituir (Ctes de GeoRasterFile)
618
     */
619
    protected void setRGBLine(BufferedImage image, int startX, int startY,
620
                              int w, int h, int[] rgbArray, int offset,
621
                              int scansize, int flags) {
622
        int[] line = new int[rgbArray.length];
623
        image.getRGB(startX, startY, w, h, line, offset, scansize);
574
						return pRGBArrayCopy;
575
				}
624 576

  
625
        if (flags == GeoRasterFile.RED_BAND) {
626
            for (int i = 0; i < line.length; i++)
627
                line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
628
        } else if (flags == GeoRasterFile.GREEN_BAND) {
629
            for (int i = 0; i < line.length; i++)
630
                line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
631
        } else if (flags == GeoRasterFile.BLUE_BAND) {
632
            for (int i = 0; i < line.length; i++)
633
                line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
634
        }
577
				return pRGBArray;
578
		}
635 579

  
636
        image.setRGB(startX, startY, w, h, line, offset, scansize);
637
    }
580
		/**
581
		 * Asigna al objeto Image los valores con los dato de la imagen contenidos en el
582
		 * vector de enteros.
583
		 * @param image        imagen con los datos actuales
584
		 * @param startX        inicio de la posici?n en X dentro de la imagen
585
		 * @param startY        inicio de la posici?n en X dentro de la imagen
586
		 * @param w        Ancho de la imagen
587
		 * @param h        Alto de la imagen
588
		 * @param rgbArray        vector que contiene la banda que se va a sustituir
589
		 * @param offset        desplazamiento
590
		 * @param scansize        tama?o de imagen recorrida por cada p
591
		 */
592
		protected void setRGBLine(BufferedImage image, int startX, int startY,
593
															int w, int h, int[] rgbArray, int offset,
594
															int scansize) {
595
				image.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
596
		}
638 597

  
639
    /**
640
     * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
641
     * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
642
     * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
643
     * banda correspondiente a flags es sustituida por los datos del vector.
644
     * @param image        imagen con los datos actuales
645
     * @param startX        inicio de la posici?n en X dentro de la imagen
646
     * @param startY        inicio de la posici?n en X dentro de la imagen
647
     * @param w        Ancho de la imagen
648
     * @param h        Alto de la imagen
649
     * @param rgbArray        vector que contiene la banda que se va a sustituir
650
     * @param offset        desplazamiento
651
     * @param scansize        tama?o de imagen recorrida por cada paso
652
     * @param origBand        Banda origen del GeoRasterFile
653
     * @param destBandFlag        banda que se va a sustituir (Ctes de GeoRasterFile)
654
     */
655
    protected void setRGBLine(BufferedImage image, int startX, int startY,
656
                              int w, int h, int[] rgbArray, int offset,
657
                              int scansize, int origBand, int destBandFlag) {
658
        int[] line = new int[rgbArray.length];
659
        image.getRGB(startX, startY, w, h, line, offset, scansize);
598
		/**
599
		 * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
600
		 * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
601
		 * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
602
		 * banda correspondiente a flags es sustituida por los datos del vector.
603
		 * @param image        imagen con los datos actuales
604
		 * @param startX        inicio de la posici?n en X dentro de la imagen
605
		 * @param startY        inicio de la posici?n en X dentro de la imagen
606
		 * @param w        Ancho de la imagen
607
		 * @param h        Alto de la imagen
608
		 * @param rgbArray        vector que contiene la banda que se va a sustituir
609
		 * @param offset        desplazamiento
610
		 * @param scansize        tama?o de imagen recorrida por cada paso
611
		 * @param flags        banda que se va a sustituir (Ctes de GeoRasterFile)
612
		 */
613
		protected void setRGBLine(BufferedImage image, int startX, int startY,
614
															int w, int h, int[] rgbArray, int offset,
615
															int scansize, int flags) {
616
				int[] line = new int[rgbArray.length];
617
				image.getRGB(startX, startY, w, h, line, offset, scansize);
660 618

  
661
        if ((origBand == 0) && (destBandFlag == GeoRasterFile.RED_BAND)) {
662
            for (int i = 0; i < line.length; i++)
663
                line[i] = (line[i] & 0xff00ffff) | (rgbArray[i] & 0x00ff0000);
664
        } else if ((origBand == 1) &&
665
                       (destBandFlag == GeoRasterFile.GREEN_BAND)) {
666
            for (int i = 0; i < line.length; i++)
667
                line[i] = (line[i] & 0xffff00ff) | (rgbArray[i] & 0x0000ff00);
668
        } else if ((origBand == 2) &&
669
                       (destBandFlag == GeoRasterFile.BLUE_BAND)) {
670
            for (int i = 0; i < line.length; i++)
671
                line[i] = (line[i] & 0xffffff00) | (rgbArray[i] & 0x000000ff);
672
        }
673
        else if ((origBand == 0) && (destBandFlag == GeoRasterFile.GREEN_BAND)) {
674
            for (int i = 0; i < line.length; i++)
675
                line[i] = (line[i] & 0xffff00ff) |
676
                          ((rgbArray[i] & 0x00ff0000) >> 8);
677
        } else if ((origBand == 0) &&
678
                       (destBandFlag == GeoRasterFile.BLUE_BAND)) {
679
            for (int i = 0; i < line.length; i++)
680
                line[i] = (line[i] & 0xffffff00) |
681
                          ((rgbArray[i] & 0x00ff0000) >> 16);
682
        }
683
        else if ((origBand == 1) && (destBandFlag == GeoRasterFile.RED_BAND)) {
684
            for (int i = 0; i < line.length; i++)
685
                line[i] = (line[i] & 0xff00ffff) |
686
                          ((rgbArray[i] & 0x0000ff00) << 8);
687
        } else if ((origBand == 1) &&
688
                       (destBandFlag == GeoRasterFile.BLUE_BAND)) {
689
            for (int i = 0; i < line.length; i++)
690
                line[i] = (line[i] & 0xffffff00) |
691
                          ((rgbArray[i] & 0x0000ff00) >> 8);
692
        }
693
        else if ((origBand == 2) && (destBandFlag == GeoRasterFile.RED_BAND)) {
694
            for (int i = 0; i < line.length; i++)
695
                line[i] = (line[i] & 0xff00ffff) |
696
                          ((rgbArray[i] & 0x000000ff) << 16);
697
        } else if ((origBand == 2) &&
698
                       (destBandFlag == GeoRasterFile.GREEN_BAND)) {
699
            for (int i = 0; i < line.length; i++)
700
                line[i] = (line[i] & 0xffff00ff) |
701
                          ((rgbArray[i] & 0x000000ff) << 8);
702
        }
619
				if (flags == GeoRasterFile.RED_BAND) {
620
						for (int i = 0; i < line.length; i++)
621
								line[i] = (line[i] & 0x0000ffff) | (rgbArray[i] & 0xffff0000);
622
				} else if (flags == GeoRasterFile.GREEN_BAND) {
623
						for (int i = 0; i < line.length; i++)
624
								line[i] = (line[i] & 0x00ff00ff) | (rgbArray[i] & 0xff00ff00);
625
				} else if (flags == GeoRasterFile.BLUE_BAND) {
626
						for (int i = 0; i < line.length; i++)
627
								line[i] = (line[i] & 0x00ffff00) | (rgbArray[i] & 0xff0000ff);
628
				}
703 629

  
704
        image.setRGB(startX, startY, w, h, line, offset, scansize);
705
    }
706
    
707
    
708
    /* (non-Javadoc)
709
     * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans, java.awt.Image, int origBand, int destBand)
710
     */
711
    public Image updateImage(int width, int height, ICoordTrans rp, Image img,
712
                             int origBand, int destBandFlag) throws SupersamplingNotSupportedException{
713
        //TODO reproyectar para devolver el trozo de imagen pedida sobre ...
714
        // la proyecci?n de destino.
715
        int line = 0;
716
        boolean mustResize = false;
717
        Dimension fullSize = null;
718
        boolean trySupersampling = false;
630
				image.setRGB(startX, startY, w, h, line, offset, scansize);
631
		}
719 632

  
720
        if (file == null) {
721
            return null;
722
        }
633
		/**
634
		 * Asigna al objeto Image la mezcla entre los valores que ya tiene y los valores
635
		 * con los dato de la imagen contenidos en el vector de enteros. De los valores RGB
636
		 * que ya contiene se mantienen las bandas que no coinciden con el valor de flags. La
637
		 * banda correspondiente a flags es sustituida por los datos del vector.
638
		 * @param image        imagen con los datos actuales
639
		 * @param startX        inicio de la posici?n en X dentro de la imagen
640
		 * @param startY        inicio de la posici?n en X dentro de la imagen
641
		 * @param w        Ancho de la imagen
642
		 * @param h        Alto de la imagen
643
		 * @param rgbArray        vector que contiene la banda que se va a sustituir
644
		 * @param offset        desplazamiento
645
		 * @param scansize        tama?o de imagen recorrida por cada paso
646
		 * @param origBand        Banda origen del GeoRasterFile
647
		 * @param destBandFlag        banda que se va a sustituir (Ctes de GeoRasterFile)
648
		 */
649
		protected void setRGBLine(BufferedImage image, int startX, int startY,
650
															int w, int h, int[] rgbArray, int offset,
651
															int scansize, int origBand, int destBandFlag) {
652
				int[] line = new int[rgbArray.length];
653
				image.getRGB(startX, startY, w, h, line, offset, scansize);
723 654

  
724
        try {
725
            int[] bandlist;
726
            int[] bandListTriband;
727
            int[] pRGBArray = null;
655
				if ((origBand == 0) && (destBandFlag == GeoRasterFile.RED_BAND)) {
656
						for (int i = 0; i < line.length; i++)
657
								line[i] = (line[i] & 0xff00ffff) | (rgbArray[i] & 0x00ff0000);
658
				} else if ((origBand == 1) &&
659
											 (destBandFlag == GeoRasterFile.GREEN_BAND)) {
660
						for (int i = 0; i < line.length; i++)
661
								line[i] = (line[i] & 0xffff00ff) | (rgbArray[i] & 0x0000ff00);
662
				} else if ((origBand == 2) &&
663
											 (destBandFlag == GeoRasterFile.BLUE_BAND)) {
664
						for (int i = 0; i < line.length; i++)
665
								line[i] = (line[i] & 0xffffff00) | (rgbArray[i] & 0x000000ff);
666
				}
667
				else if ((origBand == 0) && (destBandFlag == GeoRasterFile.GREEN_BAND)) {
668
						for (int i = 0; i < line.length; i++)
669
								line[i] = (line[i] & 0xffff00ff) |
670
													((rgbArray[i] & 0x00ff0000) >> 8);
671
				} else if ((origBand == 0) &&
672
											 (destBandFlag == GeoRasterFile.BLUE_BAND)) {
673
						for (int i = 0; i < line.length; i++)
674
								line[i] = (line[i] & 0xffffff00) |
675
													((rgbArray[i] & 0x00ff0000) >> 16);
676
				}
677
				else if ((origBand == 1) && (destBandFlag == GeoRasterFile.RED_BAND)) {
678
						for (int i = 0; i < line.length; i++)
679
								line[i] = (line[i] & 0xff00ffff) |
680
													((rgbArray[i] & 0x0000ff00) << 8);
681
				} else if ((origBand == 1) &&
682
											 (destBandFlag == GeoRasterFile.BLUE_BAND)) {
683
						for (int i = 0; i < line.length; i++)
684
								line[i] = (line[i] & 0xffffff00) |
685
													((rgbArray[i] & 0x0000ff00) >> 8);
686
				}
687
				else if ((origBand == 2) && (destBandFlag == GeoRasterFile.RED_BAND)) {
688
						for (int i = 0; i < line.length; i++)
689
								line[i] = (line[i] & 0xff00ffff) |
690
													((rgbArray[i] & 0x000000ff) << 16);
691
				} else if ((origBand == 2) &&
692
											 (destBandFlag == GeoRasterFile.GREEN_BAND)) {
693
						for (int i = 0; i < line.length; i++)
694
								line[i] = (line[i] & 0xffff00ff) |
695
													((rgbArray[i] & 0x000000ff) << 8);
696
				}
728 697

  
729
            if(mustVerifySize()){
730
	            // Work out the correct aspect for the setView call.
731
	            double dFileAspect = (double) v.width() / (double) v.height();
732
	            double dWindowAspect = (double) width / (double) height;
733
	
734
	            if (dFileAspect > dWindowAspect) {
735
	                height = (int) ((double) width / dFileAspect);
736
	            } else {
737
	                width = (int) ((double) height * dFileAspect);
738
	            }
739
            }
698
				image.setRGB(startX, startY, w, h, line, offset, scansize);
699
		}
740 700

  
741
            fullSize = new Dimension(width, height);
742
            
743
            ChunkFrame[] frames = ChunkFrame.computeFrames(file, v, fullSize, extent);
744
            	
745
            if (frames.length == 1) {
746
                width = frames[0].width;
747
                height = frames[0].height;
748 701

  
749
                if (width <= 0)
750
                    width = 1;
751
             
752
                if (height <= 0)
753
                    height = 1;
754
            }
755
                        
756
            // Create an image of the ecw file.
757
            pRGBArray = new int[width];
702
		/* (non-Javadoc)
703
		 * @see org.cresques.io.GeoRasterFile#updateImage(int, int, org.cresques.cts.ICoordTrans, java.awt.Image, int origBand, int destBand)
704
		 */
705
		public Image updateImage(int width, int height, ICoordTrans rp, Image img,
706
														 int origBand, int destBandFlag) throws SupersamplingNotSupportedException{
707
				//TODO reproyectar para devolver el trozo de imagen pedida sobre ...
708
				// la proyecci?n de destino.
709
				int line = 0;
710
				Dimension fullSize = null;
711
				boolean trySupersampling = false;
758 712

  
759
            // Setup the view parameters for the ecw file.
760
            bandlist = new int[bandCount];
761
            bandListTriband = new int[bandCount];
713
				if (file == null) {
714
						return null;
715
				}
762 716

  
763
            if (bandCount > 2) {
764
                bandlist[0] = getBand(RED_BAND);
765
                bandlist[1] = getBand(GREEN_BAND);
766
                bandlist[2] = getBand(BLUE_BAND);
717
				try {
718
						int[] bandlist;
719
						int[] bandListTriband;
720
						int[] pRGBArray = null;
767 721

  
768
                if (bandCount > 3) {
769
                    for (int i = 3; i < bandCount; i++) {
770
                        bandlist[i] = 0;
771
                    }
772
                }
773
            } else {
774
                for (int i = 0; i < bandCount; i++)
775
                    bandlist[i] = i;
776
            }
722
						if(mustVerifySize()){
723
							// Work out the correct aspect for the setView call.
724
							double dFileAspect = (double) v.width() / (double) v.height();
725
							double dWindowAspect = (double) width / (double) height;
777 726

  
778
            if (bandCount == 3) {
779
                bandListTriband[0] = 0;
780
                bandListTriband[1] = 1;
781
                bandListTriband[2] = 2;
782
            }
727
							if (dFileAspect > dWindowAspect) {
728
									height = (int) ((double) width / dFileAspect);
729
							} else {
730
									width = (int) ((double) height * dFileAspect);
731
							}
732
						}
783 733

  
784
            int[] mascara = new int[3];
785
            int[] shl = new int[3];
786
            int[] shr = new int[3];
787
            boolean order = true;
788
            
789
            if (img == null) { //Caso en el que se crea un Image
790
                EcwFile.nUpdate = 1;
734
						fullSize = new Dimension(width, height);
791 735

  
792
                Image ecwImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
736
						ChunkFrame[] frames = ChunkFrame.computeFrames(file, v, fullSize, extent);
793 737

  
794
                for (int nChunk = 0; nChunk < frames.length; nChunk++) {
795
                    ChunkFrame f = frames[nChunk];
796
                    
797
                    try{
798
	                    if (bandCount != 3) {
799
	                        setFileView(file.numBands, bandlist, f);
800
	                    } else {
801
	                        setFileView(file.numBands, bandListTriband, f);
802
	                    }
803
                    }catch(JNCSInvalidSetViewException exc){
804
                    	trySupersampling = true;
805
                    }
738
						if (frames.length == 1) {
739
								width = frames[0].width;
740
								height = frames[0].height;
806 741

  
807
                    order = calcMaskAndShift(bandlist, mascara, shl, shr);
742
								if (width <= 0)
743
										width = 1;
808 744

  
809
                    for (line = 0; line < f.height; line++) {
810
                        file.readLineRGBA(pRGBArray);
811
                        pRGBArray = changeBands(order, pRGBArray, mascara, shl, shr);
812
                        setRGBLine((BufferedImage) ecwImage, f.pos.x, f.pos.y + line, f.width, 1, pRGBArray, 0, f.width);
813
                    }
814
                } //Chuncks
745
								if (height <= 0)
746
										height = 1;
747
						}
815 748

  
816
                applyAlpha(ecwImage);
749
						// Create an image of the ecw file.
750
						pRGBArray = new int[width];
817 751

  
818
                if (frames[0].mustResize && !this.multifile)
819
                    return resizeImageII(fullSize, ecwImage);
820
                
821
                lastRefreshPercent = file.getPercentComplete();
752
						// Setup the view parameters for the ecw file.
753
						bandlist = new int[bandCount];
754
						bandListTriband = new int[bandCount];
822 755

  
823
                //System.out.println("Leido al "+lastRefreshPercent+" %.");
824
                return ecwImage;
825
            } else { //Caso en el que se actualiza una banda del Image
826
                EcwFile.nUpdate++;
756
						if (bandCount > 2) {
757
								bandlist[0] = getBand(RED_BAND);
758
								bandlist[1] = getBand(GREEN_BAND);
759
								bandlist[2] = getBand(BLUE_BAND);
827 760

  
828
                for (int nChunk = 0; nChunk < frames.length; nChunk++) {
829
                    ChunkFrame f = frames[nChunk];
761
								if (bandCount > 3) {
762
										for (int i = 3; i < bandCount; i++) {
763
												bandlist[i] = 0;
764
										}
765
								}
766
						} else {
767
								for (int i = 0; i < bandCount; i++)
768
										bandlist[i] = i;
769
						}
830 770

  
831
                    if (bandCount != 3) {
832
                        setFileView(file.numBands, bandlist, f);
833
                    } else {
834
                        setFileView(file.numBands, bandListTriband, f);
835
                    }
771
						if (bandCount == 3) {
772
								bandListTriband[0] = 0;
773
								bandListTriband[1] = 1;
774
								bandListTriband[2] = 2;
775
						}
836 776

  
837
                    order = calcMaskAndShift(bandlist, mascara, shl, shr);
838
                    
839
                    for (line = 0; line < f.height; line++) {
840
                        file.readLineRGBA(pRGBArray);
841
                        pRGBArray = changeBands(order, pRGBArray, mascara, shl, shr);
842
                        setRGBLine((BufferedImage) img, f.pos.x, f.pos.y + line, f.width, 1, pRGBArray, 0, f.width, origBand, destBandFlag);
843
                    }
844
                } //Chuncks
777
						int[] mascara = new int[3];
778
						int[] shl = new int[3];
779
						int[] shr = new int[3];
780
						boolean order = true;
845 781

  
846
                applyAlpha(img);
782
						if (img == null) { //Caso en el que se crea un Image
783
								EcwFile.nUpdate = 1;
847 784

  
848
                if (frames[0].mustResize && (nUpdate == 3) && this.multifile) {
849
                    return resizeImageII(fullSize, img);
850
                }
785
								Image ecwImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
851 786

  
852
                lastRefreshPercent = file.getPercentComplete();
787
								for (int nChunk = 0; nChunk < frames.length; nChunk++) {
788
										ChunkFrame f = frames[nChunk];
853 789

  
854
                //System.out.println("Leido al "+lastRefreshPercent+" %.");
855
                return img;
856
            }
857
        } catch (com.ermapper.ecw.JNCSException e) { //java.lang.ArrayIndexOutOfBoundsException:
858
            bErrorOnOpen = true;
859
            System.err.println("EcwFile JNCS Error en la l?nea " + line + "/" +
860
                               height);
861
            System.err.println(e.getMessage());
862
        } catch (java.lang.ArrayIndexOutOfBoundsException e) { //:
863
            bErrorOnOpen = true;
864
            System.err.println("EcwFile ArrayIndex Error en la l?nea " + line +"/" + height);
865
            System.err.println(e.getMessage());
866
        } catch (Exception e) {
867
            bErrorOnOpen = true;
868
            errorMessage = e.getMessage();
869
            System.err.println(errorMessage);
870
            if(trySupersampling)
871
            	throw new SupersamplingNotSupportedException();
872
        }
790
										try{
791
											if (bandCount != 3) {
792
													setFileView(file.numBands, bandlist, f);
793
											} else {
794
													setFileView(file.numBands, bandListTriband, f);
795
											}
796
										}catch(JNCSInvalidSetViewException exc){
797
											trySupersampling = true;
798
										}
873 799

  
874
        return img;
875
    }
800
										order = calcMaskAndShift(bandlist, mascara, shl, shr);
876 801

  
877
    private Image resizeImageII(Dimension sz, Image image) {
878
        int w = (int)sz.getWidth();
879
        int h = (int)sz.getHeight();
880
    	Image buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
881
    	
882
        //Desplazamiento para la X y la Y leidas. Estas tienen efecto cuando un pixel no empieza a visualizarse
883
        //justo en su esquina superior izquierda y tiene que ser cortado en la visualizaci?n.
884
       
885
        double currentViewX = (((double) file.width)/(Math.abs(extent.getMax().getX() - extent.getMin().getX())))*(v.minX()-file.originX);
802
										for (line = 0; line < f.height; line++) {
803
												file.readLineRGBA(pRGBArray);
804
												pRGBArray = changeBands(order, pRGBArray, mascara, shl, shr);
805
												setRGBLine((BufferedImage) ecwImage, f.pos.x, f.pos.y + line, f.width, 1, pRGBArray, 0, f.width);
806
										}
807
								} //Chuncks
808

  
809
								applyAlpha(ecwImage);
810

  
811
								if (frames[0].mustResize && !this.multifile)
812
										return resizeImageII(fullSize, ecwImage);
813

  
814
								lastRefreshPercent = file.getPercentComplete();
815

  
816
								//System.out.println("Leido al "+lastRefreshPercent+" %.");
817
								return ecwImage;
818
						} else { //Caso en el que se actualiza una banda del Image
819
								EcwFile.nUpdate++;
820

  
821
								for (int nChunk = 0; nChunk < frames.length; nChunk++) {
822
										ChunkFrame f = frames[nChunk];
823

  
824
										if (bandCount != 3) {
825
												setFileView(file.numBands, bandlist, f);
826
										} else {
827
												setFileView(file.numBands, bandListTriband, f);
828
										}
829

  
830
										order = calcMaskAndShift(bandlist, mascara, shl, shr);
831

  
832
										for (line = 0; line < f.height; line++) {
833
												file.readLineRGBA(pRGBArray);
834
												pRGBArray = changeBands(order, pRGBArray, mascara, shl, shr);
835
												setRGBLine((BufferedImage) img, f.pos.x, f.pos.y + line, f.width, 1, pRGBArray, 0, f.width, origBand, destBandFlag);
836
										}
837
								} //Chuncks
838

  
839
								applyAlpha(img);
840

  
841
								if (frames[0].mustResize && (nUpdate == 3) && this.multifile) {
842
										return resizeImageII(fullSize, img);
843
								}
844

  
845
								lastRefreshPercent = file.getPercentComplete();
846

  
847
								//System.out.println("Leido al "+lastRefreshPercent+" %.");
848
								return img;
849
						}
850
				} catch (com.ermapper.ecw.JNCSException e) { //java.lang.ArrayIndexOutOfBoundsException:
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff