Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libRaster / src / org / gvsig / raster / grid / render / ImageDrawer.java @ 20273

History | View | Annotate | Download (13.3 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.gvsig.raster.buffer.RasterBuffer;
25
import org.gvsig.raster.dataset.IBuffer;
26
import org.gvsig.raster.grid.GridTransparency;
27
import org.gvsig.raster.process.RasterTask;
28
import org.gvsig.raster.process.RasterTaskQueue;
29
/**
30
 * Objeto para la escritura de datos desde un buffer a un objeto Image. En este nivel de
31
 * renderizado no se gestiona extents, ni rotaciones ni coordenadas del mundo, solo la
32
 * escritura desde un buffer hasta otro de tama?o dado. Por medio de par?metros y de objetos
33
 * de estado varia el resultado de la escritura, selecci?n de bandas a escribir desde el buffer
34
 * a RGB, transparencias aplicadas o paletas.
35
 *
36
 * @author Nacho Brodin (nachobrodin@gmail.com)
37
 */
38
public class ImageDrawer {
39
        /**
40
         * Fuente de datos para el renderizado
41
         */
42
        private IBuffer   rasterBuf = null;
43
        private double[]  step      = null;
44
        /**
45
         * Ancho y alto del objeto image
46
         */
47
        private int       width     = 0;
48
        private int       height    = 0;
49
        private Rendering rendering = null;
50

    
51
        public ImageDrawer(Rendering rendering) {
52
                this.rendering = rendering;
53
        }
54

    
55
        /**
56
         * Dibuja el buffer sobre un objeto Image de java.awt y devuelve el resultado.
57
         *
58
         * @param replicateBand Flag de comportamiento del renderizado. Al renderizar el buffer
59
         * este obtiene la primera banda del buffer y la asigna al R, la segunda al G y la tercera
60
         * al B. Este flag no es tomado en cuenta en caso de que existan 3 bandas en el buffer.
61
         * Si no hay tres bandas, por ejemplo una y el flag es true esta ser? replicada
62
         * en R, G y B, en caso de ser false la banda ser? dibujada en su posici?n (R, G o B)
63
         * y en las otras bandas se rellenar? con 0.
64
         *
65
         * @param transparentBand. Si es true la banda 4 es alpha y si es false no lo es.
66
         *
67
         * @return java.awt.Image con el buffer dibujado.
68
         * @throws InterruptedException 
69
         */
70
        public Image drawBufferOverImageObject(boolean replicateBand, int[] renderBands) throws InterruptedException {
71
                if (rasterBuf == null || width == 0 || height == 0)
72
                        return null;
73

    
74
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
75

    
76
                // Dibujado de raster de 1 o 2 bandas.
77
                // adaptBufferToRender(replicateBand, renderBands);
78

    
79
                if (rasterBuf.getDataType() != IBuffer.TYPE_BYTE)
80
                        rasterBuf = convertToByte(rasterBuf);
81

    
82
                // Asigna la banda de transparencia si existe esta.
83
                // assignTransparencyBand(renderBands);
84

    
85
                byte[] data = new byte[rasterBuf.getBandCount()];
86

    
87
                GridTransparency transparency = rendering.getLastTransparency();
88
                if (transparency != null && transparency.getAlphaBand() != null && transparency.isTransparencyActive()) {
89
                        if (transparency.getAlphaBand().getDataType() != IBuffer.TYPE_BYTE)
90
                                transparency.setAlphaBand(convertToByte(transparency.getAlphaBand()));
91
                        drawWithTransparency(image, data, (step != null));
92
                } else
93
                        drawByte(image, data, (step != null));
94

    
95
                step = null;
96
                return image;
97
        }
98

    
99
        /**
100
         * Calcula los vectores de desplazamiento en pixels en X e Y cuando se supersamplea.
101
         * @param r Array de desplazamientos para las filas. Debe tener espacio reservado
102
         * @param c Array de desplazamientos para las columnas. Debe tener espacio reservado
103
         * cargados.
104
         */
105
        private void calcSupersamplingStepsArrays(int[] r, int[] c) {
106
                double pos = step[1];
107
                for(int row = 0; row < r.length; row ++) {
108
                        r[row] = (int)(pos / step[3]);
109
                        pos ++;
110
                }
111
                pos = step[0];
112
                for(int col = 0; col < c.length; col ++) {
113
                        c[col] = (int)(pos / step[2]);
114
                        pos ++;
115
                }
116
        }
117

    
118
        /**
119
         * Dibuja un raster sobre un BufferedImage
120
         * @param image BufferedImage sobre el que se dibuja
121
         * @param data buffer vacio. Se trata de un array de bytes donde cada elemento representa una banda.
122
         * @param supersampling true si se necesita supersamplear y false si no se necesita
123
         * @throws InterruptedException 
124
         */
125
        private void drawByte(BufferedImage image, byte[] data, boolean supersampling) throws InterruptedException {
126
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
127

    
128
                if (supersampling) {
129
                        int[] r = new int[height];
130
                        int[] c = new int[width];
131
                        calcSupersamplingStepsArrays(r, c);
132
                        for (int row = 0; row < height; row++) {
133
                                for (int col = 0; col < width; col++) {
134
                                        try {
135
                                                rasterBuf.getElemByte(r[row], c[col], data);
136
                                                image.setRGB(col, row, (0xff000000 + ((data[0] & 0xff) << 16)
137
                                                                + ((data[1] & 0xff) << 8) + (data[2] & 0xff)));
138
                                        } catch (ArrayIndexOutOfBoundsException e) {
139
                                                System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight());
140
                                                System.err.println("== Position required:" + col + " " + row);
141
                                                break;
142
                                        }
143
                                }
144
                                if (task.getEvent() != null)
145
                                        task.manageEvent(task.getEvent());
146
                        }
147
                } else {
148
                        for (int row = 0; row < rasterBuf.getHeight(); row++) {
149
                                for (int col = 0; col < rasterBuf.getWidth(); col++) {
150
                                        try {
151
                                                rasterBuf.getElemByte(row, col, data);
152
                                                image.setRGB(col, row, (0xff000000 + ((data[0] & 0xff) << 16)
153
                                                                + ((data[1] & 0xff) << 8) + (data[2] & 0xff)));
154
                                        } catch (ArrayIndexOutOfBoundsException ex) {
155
                                                System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight());
156
                                                System.err.println("== Position required:" + col + " " + row);
157
                                                break;
158
                                        }
159
                                }
160
                                if (task.getEvent() != null)
161
                                        task.manageEvent(task.getEvent());
162
                        }
163
                }
164
        }
165

    
166
        /**
167
         * Dibuja un raster sobre un BufferedImage con las propiedades de paleta y transparencia
168
         * @param image BufferedImage sobre el que se dibuja
169
         * @param data buffer vacio. Se trata de un array de bytes donde cada elemento representa una banda.
170
         * @param supersampling true si se necesita supersamplear y false si no se necesita
171
         * @throws InterruptedException 
172
         */
173
        private void drawWithTransparency(BufferedImage image, byte[] data, boolean supersampling) throws InterruptedException {
174
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
175
                int value = 0;
176
                GridTransparency transparency = rendering.getLastTransparency();
177
//                try {
178
                if (supersampling) {
179
                        int[] r = new int[height];
180
                        int[] c = new int[width];
181
                        calcSupersamplingStepsArrays(r, c);
182
                        for (int row = 0; row < height; row++) {
183
                                for (int col = 0; col < width; col++) {
184
                                        try {
185
                                                rasterBuf.getElemByte(r[row], c[col], data);
186
                                                value = transparency.processRGB(data[0] & 0xff, data[1] & 0xff, data[2] & 0xff, r[row], c[col]);
187
                                                image.setRGB(col, row, value);
188
                                        } catch (ArrayIndexOutOfBoundsException e) {
189
                                                System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight());
190
                                                System.err.println("== Position required:" + col + " " + row);
191
                                                break;
192
                                        }
193
                                }
194
                                if (task.getEvent() != null)
195
                                        task.manageEvent(task.getEvent());
196
                        }
197
                } else {
198
                        for (int row = 0; row < rasterBuf.getHeight(); row++) {
199
                                for (int col = 0; col < rasterBuf.getWidth(); col++) {
200
                                        try {
201
                                                rasterBuf.getElemByte(row, col, data);
202
                                                value = transparency.processRGB(data[0] & 0xff, data[1] & 0xff, data[2] & 0xff, row, col);
203
                                                image.setRGB(col, row, value);
204
                                        } catch (ArrayIndexOutOfBoundsException e) {
205
                                                System.err.println("== Size Image:" + image.getWidth() + " " + image.getHeight());
206
                                                System.err.println("== Position required:" + col + " " + row);
207
                                                break;
208
                                        }
209
                                }
210
                                if (task.getEvent() != null)
211
                                        task.manageEvent(task.getEvent());
212
                        }
213
                }
214
//                } finally {
215
//                        Quitamos el uso del free para no invocar al garbage collector en numerosas
216
//                        iteraciones
217
//                        transparency.free();
218
//                }
219
        }
220
        /**
221
         * Intercala bandas en el buffer dependiendo de si hay que replicar o meter
222
         * bandas en negro. Esto tiene es valido para buffers con solo una banda ya que
223
         * el dibujado sobre Graphics debe ser R, G, B.
224
         *
225
         * @param replicateBand false si no se replican bandas y las que no existen
226
         * se ponen en negro y false si hay que dibujar la misma en R,G y B. Esto
227
         * tiene sentido si el raster tiene solo 1 o 2 bandas.
228
         * @param renderBands array con las posiciones de renderizado.
229
         *  A la hora de renderizar hay que tener en cuenta que solo se renderizan las
230
         * tres primeras bandas del buffer por lo que solo se tienen en cuenta los tres primeros
231
         * elementos. Por ejemplo, el array {1, 0, 3} dibujar? sobre el Graphics las bandas 1,0 y 3 de un
232
         * raster de al menos 4 bandas.La notaci?n con -1 en alguna posici?n del vector solo tiene sentido
233
         * en la visualizaci?n pero no se puede as?gnar una banda del buffer a null.
234
         * Algunos ejemplos:
235
         * <P>
236
         * {-1, 0, -1} Dibuja la banda 0 del raster en la G de la visualizaci?n.
237
         * Si replicateBand es true R = G = B sino R = B = 0
238
         * {1, 0, 3} La R = banda 1 del raster, G = 0 y B = 3
239
         * {0} La R = banda 0 del raster. Si replicateBand es true R = G = B sino G = B = 0
240
         * </P>
241
         */
242
        /*private void adaptBufferToRender(boolean replicateBand, int[] renderBands){
243
                byte[][] aux = null;
244
                if(rasterBuf.getBandCount() < 3){
245
                        for(int i = 0; i < renderBands.length; i++){
246
                                if( replicateBand && renderBands[i] == -1)
247
                                        rasterBuf.replicateBand(0, i);
248
                                if( !replicateBand && renderBands[i] == -1){
249
                                        if(aux == null)
250
                                                aux = rasterBuf.createByteBand(rasterBuf.getWidth(), rasterBuf.getHeight(), (byte)0);
251
                                        rasterBuf.addBandByte(i, aux);
252
                                }
253
                        }
254
                }
255
        }*/
256

    
257
        /**
258
         * Asigna al objeto GridTransparency la banda de transparencia si la tiene para
259
         * tenerla en cuenta en el renderizado.
260
         * @param renderBands Lista de bandas a renderizar
261
         * @param ts Objeto con las propiedades de transparencia del Grid.
262
         */
263
        /*private void assignTransparencyBand(int[] renderBands) {
264
                if(transparency != null){
265
                        for(int i = 0; i < transparency.getTransparencyBandNumberList().size(); i ++) {
266
                                for(int j = 0; j < renderBands.length; j ++) {
267
                                        if(renderBands[j] == ((Integer)transparency.getTransparencyBandNumberList().get(i)).intValue()){
268
                                                if(transparency.getBand() == null)
269
                                                        transparency.setBand(rasterBuf.getBandBuffer(renderBands[j]));
270
                                                else {
271
                                                        IBuffer outBuf = transparency.getBand().cloneBuffer();
272
                                                        transparency.mergeTransparencyBands(new IBuffer[]{transparency.getBand(), rasterBuf.getBandBuffer(renderBands[j])}, outBuf);
273
                                                }
274
                                        }
275
                                }
276
                        }
277
                }
278
        }*/
279

    
280
        private IBuffer convertToByte(IBuffer buf) {
281
                IBuffer b = RasterBuffer.getBuffer(IBuffer.TYPE_BYTE, buf.getWidth(), buf.getHeight(), buf.getBandCount(), true);
282
                if(buf.getDataType() == IBuffer.TYPE_SHORT) {
283
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
284
                                for (int row = 0; row < buf.getHeight(); row++)
285
                                        for (int col = 0; col < buf.getWidth(); col++)
286
                                                b.setElem(row, col, nBand, (byte)(buf.getElemShort(row, col, nBand) & 0xffff));
287
                }
288
                if(buf.getDataType() == IBuffer.TYPE_INT) {
289
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
290
                                for (int row = 0; row < buf.getHeight(); row++)
291
                                        for (int col = 0; col < buf.getWidth(); col++)
292
                                                b.setElem(row, col, nBand, (byte)(buf.getElemInt(row, col, nBand) & 0xffffffff));
293
                }
294
                if(buf.getDataType() == IBuffer.TYPE_FLOAT) {
295
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
296
                                for (int row = 0; row < buf.getHeight(); row++)
297
                                        for (int col = 0; col < buf.getWidth(); col++)
298
                                                b.setElem(row, col, nBand, (byte)(Math.round(buf.getElemFloat(row, col, nBand))));
299
                }
300
                if(buf.getDataType() == IBuffer.TYPE_DOUBLE) {
301
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
302
                                for (int row = 0; row < buf.getHeight(); row++)
303
                                        for (int col = 0; col < buf.getWidth(); col++)
304
                                                b.setElem(row, col, nBand, (byte)(Math.round(buf.getElemDouble(row, col, nBand))));
305
                }
306
                return b;
307
        }
308

    
309
        /**
310
         * Asigna el buffer a renderizar
311
         * @param b Buffer a renderizar
312
         */
313
        public void setBuffer(IBuffer b) {
314
                this.rasterBuf = b;
315
        }
316

    
317
        /**
318
         * Asigna la paleta asociada al grid
319
         * @param palette
320
         */
321
        /*public void setPalette(GridPalette palette) {
322
                this.palette = palette;
323
        }*/
324

    
325
        /**
326
         * Asigna el desplazamiento en pixeles desde la esquina superior izquierda. Si es null se considera que esta
327
         * funci?n la ha hecho el driver quedando desactivada en el renderizador. Si es as? no debe variar el resultado
328
         * en la visualizacion.
329
         * Si Supersamplea el renderizador se cargar? una matriz de datos 1:1 por lo que se podr? aplicar un filtro
330
         * a este buffer de datos leidos independientemente del zoom que tengamos.
331
         * @param step Desplazamiento
332
         */
333
        public void setStep(double[] step) {
334
                this.step = step;
335
        }
336

    
337
        /**
338
         * Asigna el ancho y el alto del BufferedImage. Esto es util para cuando hay supersampling
339
         * que el tama?o del objeto Image no coincide con el buffer con los datos raster.
340
         * @param w Ancho
341
         * @param h Alto
342
         */
343
        public void setBufferSize(int w, int h) {
344
                this.width = w;
345
                this.height = h;
346
        }
347

    
348
}