svn-gvsig-desktop / trunk / libraries / libRaster / src / org / gvsig / raster / grid / render / ImageDrawer.java @ 28321
History | View | Annotate | Download (13.7 KB)
1 |
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
|
---|---|
2 |
*
|
3 |
* Copyright (C) 2006 IVER T.I. and Generalitat Valenciana.
|
4 |
*
|
5 |
* This program is free software; you can redistribute it and/or
|
6 |
* modify it under the terms of the GNU General Public License
|
7 |
* as published by the Free Software Foundation; either version 2
|
8 |
* of the License, or (at your option) any later version.
|
9 |
*
|
10 |
* This program is distributed in the hope that it will be useful,
|
11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
13 |
* GNU General Public License for more details.
|
14 |
*
|
15 |
* You should have received a copy of the GNU General Public License
|
16 |
* along with this program; if not, write to the Free Software
|
17 |
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
|
18 |
*/
|
19 |
package org.gvsig.raster.grid.render; |
20 |
|
21 |
import java.awt.Image; |
22 |
import java.awt.image.BufferedImage; |
23 |
|
24 |
import org.apache.log4j.Logger; |
25 |
import org.gvsig.raster.buffer.RasterBuffer; |
26 |
import org.gvsig.raster.dataset.IBuffer; |
27 |
import org.gvsig.raster.grid.GridTransparency; |
28 |
import org.gvsig.raster.process.RasterTask; |
29 |
import org.gvsig.raster.process.RasterTaskQueue; |
30 |
/**
|
31 |
* Objeto para la escritura de datos desde un buffer a un objeto Image. En este nivel de
|
32 |
* renderizado no se gestiona extents, ni rotaciones ni coordenadas del mundo, solo la
|
33 |
* escritura desde un buffer hasta otro de tama?o dado. Por medio de par?metros y de objetos
|
34 |
* de estado varia el resultado de la escritura, selecci?n de bandas a escribir desde el buffer
|
35 |
* a RGB, transparencias aplicadas o paletas.
|
36 |
*
|
37 |
* @author Nacho Brodin (nachobrodin@gmail.com)
|
38 |
*/
|
39 |
public class ImageDrawer { |
40 |
/**
|
41 |
* Fuente de datos para el renderizado
|
42 |
*/
|
43 |
private IBuffer rasterBuf = null; |
44 |
private double[] step = null; |
45 |
/**
|
46 |
* Ancho y alto del objeto image
|
47 |
*/
|
48 |
private int width = 0; |
49 |
private int height = 0; |
50 |
private Rendering rendering = null; |
51 |
|
52 |
public ImageDrawer(Rendering rendering) {
|
53 |
this.rendering = rendering;
|
54 |
} |
55 |
|
56 |
/**
|
57 |
* Dibuja el buffer sobre un objeto Image de java.awt y devuelve el resultado.
|
58 |
*
|
59 |
* @param replicateBand Flag de comportamiento del renderizado. Al renderizar el buffer
|
60 |
* este obtiene la primera banda del buffer y la asigna al R, la segunda al G y la tercera
|
61 |
* al B. Este flag no es tomado en cuenta en caso de que existan 3 bandas en el buffer.
|
62 |
* Si no hay tres bandas, por ejemplo una y el flag es true esta ser? replicada
|
63 |
* en R, G y B, en caso de ser false la banda ser? dibujada en su posici?n (R, G o B)
|
64 |
* y en las otras bandas se rellenar? con 0.
|
65 |
*
|
66 |
* @param transparentBand. Si es true la banda 4 es alpha y si es false no lo es.
|
67 |
*
|
68 |
* @return java.awt.Image con el buffer dibujado.
|
69 |
* @throws InterruptedException
|
70 |
*/
|
71 |
public Image drawBufferOverImageObject(boolean replicateBand, int[] renderBands) throws InterruptedException { |
72 |
if (rasterBuf == null || width == 0 || height == 0) |
73 |
return null; |
74 |
|
75 |
try { // Temporal para la traza de un error aleatorio |
76 |
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); |
77 |
|
78 |
// Dibujado de raster de 1 o 2 bandas.
|
79 |
// adaptBufferToRender(replicateBand, renderBands);
|
80 |
|
81 |
if (rasterBuf.getDataType() != IBuffer.TYPE_BYTE)
|
82 |
rasterBuf = convertToByte(rasterBuf); |
83 |
|
84 |
// Asigna la banda de transparencia si existe esta.
|
85 |
// assignTransparencyBand(renderBands);
|
86 |
|
87 |
byte[] data = new byte[rasterBuf.getBandCount()]; |
88 |
|
89 |
GridTransparency transparency = rendering.getLastTransparency(); |
90 |
if (transparency != null && transparency.isTransparencyActive()) { |
91 |
if (transparency.existAlphaBand() &&
|
92 |
transparency.getAlphaBand() != null &&
|
93 |
(transparency.getAlphaBand().getDataType() != IBuffer.TYPE_BYTE)) |
94 |
transparency.setAlphaBand(convertToByte(transparency.getAlphaBand())); |
95 |
drawWithTransparency(image, data, (step != null));
|
96 |
} else
|
97 |
drawByte(image, data, (step != null));
|
98 |
|
99 |
step = null;
|
100 |
return image;
|
101 |
} catch (OutOfMemoryError error) { // Temporal para la traza de un error |
102 |
// aleatorio
|
103 |
Logger.getLogger(this.getClass()).debug( |
104 |
"Buffer: " + width + " " + height + " RenderBands: " |
105 |
+ renderBands, error); |
106 |
} |
107 |
return null; |
108 |
} |
109 |
|
110 |
/**
|
111 |
* Calcula los vectores de desplazamiento en pixels en X e Y cuando se supersamplea.
|
112 |
* @param r Array de desplazamientos para las filas. Debe tener espacio reservado
|
113 |
* @param c Array de desplazamientos para las columnas. Debe tener espacio reservado
|
114 |
* cargados.
|
115 |
*/
|
116 |
private void calcSupersamplingStepsArrays(int[] r, int[] c) { |
117 |
double pos = step[1]; |
118 |
for(int row = 0; row < r.length; row ++) { |
119 |
r[row] = (int)(pos / step[3]); |
120 |
pos ++; |
121 |
} |
122 |
pos = step[0];
|
123 |
for(int col = 0; col < c.length; col ++) { |
124 |
c[col] = (int)(pos / step[2]); |
125 |
pos ++; |
126 |
} |
127 |
} |
128 |
|
129 |
/**
|
130 |
* Dibuja un raster sobre un BufferedImage
|
131 |
* @param image BufferedImage sobre el que se dibuja
|
132 |
* @param data buffer vacio. Se trata de un array de bytes donde cada elemento representa una banda.
|
133 |
* @param supersampling true si se necesita supersamplear y false si no se necesita
|
134 |
* @throws InterruptedException
|
135 |
*/
|
136 |
private void drawByte(BufferedImage image, byte[] data, boolean supersampling) throws InterruptedException { |
137 |
RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
|
138 |
|
139 |
if (supersampling) {
|
140 |
int[] r = new int[height]; |
141 |
int[] c = new int[width]; |
142 |
calcSupersamplingStepsArrays(r, c); |
143 |
for (int row = 0; row < height; row++) { |
144 |
for (int col = 0; col < width; col++) { |
145 |
try {
|
146 |
rasterBuf.getElemByte(r[row], c[col], data); |
147 |
image.setRGB(col, row, (0xff000000 + ((data[0] & 0xff) << 16) |
148 |
+ ((data[1] & 0xff) << 8) + (data[2] & 0xff))); |
149 |
} catch (ArrayIndexOutOfBoundsException e) { |
150 |
System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight()); |
151 |
System.err.println("== Position required:" + col + " " + row); |
152 |
break;
|
153 |
} |
154 |
} |
155 |
if (task.getEvent() != null) |
156 |
task.manageEvent(task.getEvent()); |
157 |
} |
158 |
} else {
|
159 |
for (int row = 0; row < rasterBuf.getHeight(); row++) { |
160 |
for (int col = 0; col < rasterBuf.getWidth(); col++) { |
161 |
try {
|
162 |
rasterBuf.getElemByte(row, col, data); |
163 |
image.setRGB(col, row, (0xff000000 + ((data[0] & 0xff) << 16) |
164 |
+ ((data[1] & 0xff) << 8) + (data[2] & 0xff))); |
165 |
} catch (ArrayIndexOutOfBoundsException ex) { |
166 |
System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight()); |
167 |
System.err.println("== Position required:" + col + " " + row); |
168 |
break;
|
169 |
} |
170 |
} |
171 |
if (task.getEvent() != null) |
172 |
task.manageEvent(task.getEvent()); |
173 |
} |
174 |
} |
175 |
} |
176 |
|
177 |
/**
|
178 |
* Dibuja un raster sobre un BufferedImage con las propiedades de paleta y transparencia
|
179 |
* @param image BufferedImage sobre el que se dibuja
|
180 |
* @param data buffer vacio. Se trata de un array de bytes donde cada elemento representa una banda.
|
181 |
* @param supersampling true si se necesita supersamplear y false si no se necesita
|
182 |
* @throws InterruptedException
|
183 |
*/
|
184 |
private void drawWithTransparency(BufferedImage image, byte[] data, boolean supersampling) throws InterruptedException { |
185 |
RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
|
186 |
int value = 0; |
187 |
GridTransparency transparency = rendering.getLastTransparency(); |
188 |
// try {
|
189 |
if (supersampling) {
|
190 |
int[] r = new int[height]; |
191 |
int[] c = new int[width]; |
192 |
calcSupersamplingStepsArrays(r, c); |
193 |
for (int row = 0; row < height; row++) { |
194 |
for (int col = 0; col < width; col++) { |
195 |
try {
|
196 |
rasterBuf.getElemByte(r[row], c[col], data); |
197 |
value = transparency.processRGB(data[0] & 0xff, data[1] & 0xff, data[2] & 0xff, r[row], c[col]); |
198 |
image.setRGB(col, row, value); |
199 |
} catch (ArrayIndexOutOfBoundsException e) { |
200 |
System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight()); |
201 |
System.err.println("== Position required:" + col + " " + row); |
202 |
break;
|
203 |
} |
204 |
} |
205 |
if (task.getEvent() != null) |
206 |
task.manageEvent(task.getEvent()); |
207 |
} |
208 |
} else {
|
209 |
for (int row = 0; row < rasterBuf.getHeight(); row++) { |
210 |
for (int col = 0; col < rasterBuf.getWidth(); col++) { |
211 |
try {
|
212 |
rasterBuf.getElemByte(row, col, data); |
213 |
value = transparency.processRGB(data[0] & 0xff, data[1] & 0xff, data[2] & 0xff, row, col); |
214 |
image.setRGB(col, row, value); |
215 |
} catch (ArrayIndexOutOfBoundsException e) { |
216 |
System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight()); |
217 |
System.err.println("== Position required:" + col + " " + row); |
218 |
break;
|
219 |
} |
220 |
} |
221 |
if (task.getEvent() != null) |
222 |
task.manageEvent(task.getEvent()); |
223 |
} |
224 |
} |
225 |
// } finally {
|
226 |
// Quitamos el uso del free para no invocar al garbage collector en numerosas
|
227 |
// iteraciones
|
228 |
// transparency.free();
|
229 |
// }
|
230 |
} |
231 |
/**
|
232 |
* Intercala bandas en el buffer dependiendo de si hay que replicar o meter
|
233 |
* bandas en negro. Esto tiene es valido para buffers con solo una banda ya que
|
234 |
* el dibujado sobre Graphics debe ser R, G, B.
|
235 |
*
|
236 |
* @param replicateBand false si no se replican bandas y las que no existen
|
237 |
* se ponen en negro y false si hay que dibujar la misma en R,G y B. Esto
|
238 |
* tiene sentido si el raster tiene solo 1 o 2 bandas.
|
239 |
* @param renderBands array con las posiciones de renderizado.
|
240 |
* A la hora de renderizar hay que tener en cuenta que solo se renderizan las
|
241 |
* tres primeras bandas del buffer por lo que solo se tienen en cuenta los tres primeros
|
242 |
* elementos. Por ejemplo, el array {1, 0, 3} dibujar? sobre el Graphics las bandas 1,0 y 3 de un
|
243 |
* raster de al menos 4 bandas.La notaci?n con -1 en alguna posici?n del vector solo tiene sentido
|
244 |
* en la visualizaci?n pero no se puede as?gnar una banda del buffer a null.
|
245 |
* Algunos ejemplos:
|
246 |
* <P>
|
247 |
* {-1, 0, -1} Dibuja la banda 0 del raster en la G de la visualizaci?n.
|
248 |
* Si replicateBand es true R = G = B sino R = B = 0
|
249 |
* {1, 0, 3} La R = banda 1 del raster, G = 0 y B = 3
|
250 |
* {0} La R = banda 0 del raster. Si replicateBand es true R = G = B sino G = B = 0
|
251 |
* </P>
|
252 |
*/
|
253 |
/*private void adaptBufferToRender(boolean replicateBand, int[] renderBands){
|
254 |
byte[][] aux = null;
|
255 |
if(rasterBuf.getBandCount() < 3){
|
256 |
for(int i = 0; i < renderBands.length; i++){
|
257 |
if( replicateBand && renderBands[i] == -1)
|
258 |
rasterBuf.replicateBand(0, i);
|
259 |
if( !replicateBand && renderBands[i] == -1){
|
260 |
if(aux == null)
|
261 |
aux = rasterBuf.createByteBand(rasterBuf.getWidth(), rasterBuf.getHeight(), (byte)0);
|
262 |
rasterBuf.addBandByte(i, aux);
|
263 |
}
|
264 |
}
|
265 |
}
|
266 |
}*/
|
267 |
|
268 |
/**
|
269 |
* Asigna al objeto GridTransparency la banda de transparencia si la tiene para
|
270 |
* tenerla en cuenta en el renderizado.
|
271 |
* @param renderBands Lista de bandas a renderizar
|
272 |
* @param ts Objeto con las propiedades de transparencia del Grid.
|
273 |
*/
|
274 |
/*private void assignTransparencyBand(int[] renderBands) {
|
275 |
if(transparency != null){
|
276 |
for(int i = 0; i < transparency.getTransparencyBandNumberList().size(); i ++) {
|
277 |
for(int j = 0; j < renderBands.length; j ++) {
|
278 |
if(renderBands[j] == ((Integer)transparency.getTransparencyBandNumberList().get(i)).intValue()){
|
279 |
if(transparency.getBand() == null)
|
280 |
transparency.setBand(rasterBuf.getBandBuffer(renderBands[j]));
|
281 |
else {
|
282 |
IBuffer outBuf = transparency.getBand().cloneBuffer();
|
283 |
transparency.mergeTransparencyBands(new IBuffer[]{transparency.getBand(), rasterBuf.getBandBuffer(renderBands[j])}, outBuf);
|
284 |
}
|
285 |
}
|
286 |
}
|
287 |
}
|
288 |
}
|
289 |
}*/
|
290 |
|
291 |
private IBuffer convertToByte(IBuffer buf) throws InterruptedException { |
292 |
IBuffer b = RasterBuffer.getBuffer(IBuffer.TYPE_BYTE, buf.getWidth(), buf.getHeight(), buf.getBandCount(), true);
|
293 |
if(buf.getDataType() == IBuffer.TYPE_SHORT) {
|
294 |
for (int nBand = 0; nBand < buf.getBandCount(); nBand++) |
295 |
for (int row = 0; row < buf.getHeight(); row++) |
296 |
for (int col = 0; col < buf.getWidth(); col++) |
297 |
b.setElem(row, col, nBand, (byte)(buf.getElemShort(row, col, nBand) & 0xffff)); |
298 |
} |
299 |
if(buf.getDataType() == IBuffer.TYPE_INT) {
|
300 |
for (int nBand = 0; nBand < buf.getBandCount(); nBand++) |
301 |
for (int row = 0; row < buf.getHeight(); row++) |
302 |
for (int col = 0; col < buf.getWidth(); col++) |
303 |
b.setElem(row, col, nBand, (byte)(buf.getElemInt(row, col, nBand) & 0xffffffff)); |
304 |
} |
305 |
if(buf.getDataType() == IBuffer.TYPE_FLOAT) {
|
306 |
for (int nBand = 0; nBand < buf.getBandCount(); nBand++) |
307 |
for (int row = 0; row < buf.getHeight(); row++) |
308 |
for (int col = 0; col < buf.getWidth(); col++) |
309 |
b.setElem(row, col, nBand, (byte)(Math.round(buf.getElemFloat(row, col, nBand)))); |
310 |
} |
311 |
if(buf.getDataType() == IBuffer.TYPE_DOUBLE) {
|
312 |
for (int nBand = 0; nBand < buf.getBandCount(); nBand++) |
313 |
for (int row = 0; row < buf.getHeight(); row++) |
314 |
for (int col = 0; col < buf.getWidth(); col++) |
315 |
b.setElem(row, col, nBand, (byte)(Math.round(buf.getElemDouble(row, col, nBand)))); |
316 |
} |
317 |
return b;
|
318 |
} |
319 |
|
320 |
/**
|
321 |
* Asigna el buffer a renderizar
|
322 |
* @param b Buffer a renderizar
|
323 |
*/
|
324 |
public void setBuffer(IBuffer b) { |
325 |
this.rasterBuf = b;
|
326 |
} |
327 |
|
328 |
/**
|
329 |
* Asigna la paleta asociada al grid
|
330 |
* @param palette
|
331 |
*/
|
332 |
/*public void setPalette(GridPalette palette) {
|
333 |
this.palette = palette;
|
334 |
}*/
|
335 |
|
336 |
/**
|
337 |
* Asigna el desplazamiento en pixeles desde la esquina superior izquierda. Si es null se considera que esta
|
338 |
* funci?n la ha hecho el driver quedando desactivada en el renderizador. Si es as? no debe variar el resultado
|
339 |
* en la visualizacion.
|
340 |
* Si Supersamplea el renderizador se cargar? una matriz de datos 1:1 por lo que se podr? aplicar un filtro
|
341 |
* a este buffer de datos leidos independientemente del zoom que tengamos.
|
342 |
* @param step Desplazamiento
|
343 |
*/
|
344 |
public void setStep(double[] step) { |
345 |
this.step = step;
|
346 |
} |
347 |
|
348 |
/**
|
349 |
* Asigna el ancho y el alto del BufferedImage. Esto es util para cuando hay supersampling
|
350 |
* que el tama?o del objeto Image no coincide con el buffer con los datos raster.
|
351 |
* @param w Ancho
|
352 |
* @param h Alto
|
353 |
*/
|
354 |
public void setBufferSize(int w, int h) { |
355 |
this.width = w;
|
356 |
this.height = h;
|
357 |
} |
358 |
|
359 |
} |