Statistics
| Revision:

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

History | View | Annotate | Download (12.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.GridPalette;
27
import org.gvsig.raster.grid.GridTransparency;
28
/**
29
 * Objeto para la escritura de datos desde un buffer a un objeto Image. En este nivel de 
30
 * renderizado no se gestiona extents, ni rotaciones ni coordenadas del mundo, solo la
31
 * escritura desde un buffer hasta otro de tama?o dado. Por medio de par?metros y de objetos
32
 * de estado varia el resultado de la escritura, selecci?n de bandas a escribir desde el buffer
33
 * a RGB, transparencias aplicadas o paletas.
34
 * 
35
 * @author Nacho Brodin (nachobrodin@gmail.com)
36
 */
37
public class ImageDrawer {
38
        /**
39
         * Fuente de datos para el renderizado
40
         */
41
        private IBuffer                                rasterBuf = null;
42
        private GridTransparency        transparency = null;
43
        private int[]                                step = null;
44
        /**
45
         * Ancho y alto del objeto image
46
         */
47
        private int                                 width = 0;
48
        private int                                 height = 0;
49
        /**
50
         * Ancho y alto en pixeles del ?ltimo buffer asignado
51
         */
52
        private double                                         nWidth = 0;
53
        private double                                         nHeight = 0;
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
         */
69
        public Image drawBufferOverImageObject(boolean replicateBand, int[] renderBands){
70
                if(rasterBuf == null)
71
                        return null;
72

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

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

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

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

    
84
                byte[] data = new byte[rasterBuf.getBandCount()];
85
                if(transparency != null && transparency.isTransparencyActive())
86
                        drawWithTransparency(image, data, (step != null));
87
                else
88
                        drawByte(image, data, (step != null));
89

    
90
                step = null;
91
                return image;
92
        }
93

    
94
        /**
95
         * Calcula los vectores de desplazamiento en pixels en X e Y cuando se supersamplea. 
96
         * @param r Array de desplazamientos para las filas. Debe tener espacio reservado
97
         * @param c Array de desplazamientos para las columnas. Debe tener espacio reservado 
98
         * @param rel relaci?n entre el ancho o alto del objeto Image y el ancho o alto del buffer con los pixels
99
         * cargados.
100
         */
101
        private void calcSupersamplingStepsArrays(int[] r, int[] c, double rel) {
102
                for(int row = 0; row < r.length; row ++)
103
                        r[row] = (int)((row + step[1]) / rel);
104

    
105
                for(int col = 0; col < c.length; col ++)
106
                        c[col] = (int)((col + step[0]) / rel);
107
        }
108

    
109
        /**
110
         * Dibuja un raster sobre un BufferedImage
111
         * @param image BufferedImage sobre el que se dibuja
112
         * @param data buffer vacio. Se trata de un array de bytes donde cada elemento representa una banda.
113
         * @param supersampling true si se necesita supersamplear y false si no se necesita
114
         */
115
        private void drawByte(BufferedImage image, byte[] data, boolean supersampling) {
116
                if(supersampling) {
117
                        int[] r = new int[height];
118
                        int[] c = new int[width];
119
                        calcSupersamplingStepsArrays(r, c, (double)((double)height / nHeight));
120
                        for(int row = 0; row < height; row ++) {
121
                                for(int col = 0; col < width; col ++) {
122
                                        try {
123
                                                rasterBuf.getElemByte(r[row], c[col], data);
124
                                                image.setRGB(col, row, (0xff000000 + ((data[0] & 0xff) << 16) + ((data[1] & 0xff) << 8) + (data[2] & 0xff)));
125
                                        } catch(ArrayIndexOutOfBoundsException e){}
126
                                }
127
                        }
128
                } else {
129
                        for(int row = 0; row < rasterBuf.getHeight(); row ++) {
130
                                for(int col = 0; col < rasterBuf.getWidth(); col ++) {
131
                                        rasterBuf.getElemByte(row, col, data);
132
                                        image.setRGB(col, row, (0xff000000 + ((data[0] & 0xff) << 16) + ((data[1] & 0xff) << 8) + (data[2] & 0xff)));
133
                                }
134
                        }
135
                }
136
        }
137

    
138
        /**
139
         * Dibuja un raster sobre un BufferedImage con las propiedades de paleta y transparencia
140
         * @param image BufferedImage sobre el que se dibuja
141
         * @param data buffer vacio. Se trata de un array de bytes donde cada elemento representa una banda.
142
         * @param supersampling true si se necesita supersamplear y false si no se necesita
143
         */
144
        private void drawWithTransparency(BufferedImage image, byte[] data, boolean supersampling) {
145
                int value = 0;
146
                if(supersampling) {
147
                        int[] r = new int[height];
148
                        int[] c = new int[width];
149
                        calcSupersamplingStepsArrays(r, c, (double)((double)height/ nHeight));
150
                        for(int row = 0; row < height; row ++) {
151
                                for(int col = 0; col < width; col ++) {
152
                                        try{
153
                                                rasterBuf.getElemByte(r[row], c[col], data);
154
                                                value = transparency.processRGB(0xff000000 + ((data[0] & 0xff) << 16) + ((data[1] & 0xff) << 8) + (data[2] & 0xff), r[row], c[col]);
155
                                                image.setRGB(col, row, value);
156
                                        } catch(ArrayIndexOutOfBoundsException e){}
157
                                }
158
                        }
159
                } else {
160
                        for(int row = 0; row < rasterBuf.getHeight(); row ++) {
161
                                for(int col = 0; col < rasterBuf.getWidth(); col ++) {
162
                                        rasterBuf.getElemByte(row, col, data);
163
                                        value = transparency.processRGB(0xff000000 + ((data[0] & 0xff) << 16) + ((data[1] & 0xff) << 8) + (data[2] & 0xff), row, col);
164
                                        image.setRGB(col, row, value);
165
                                }
166
                        }
167
                }
168
        }
169
        /**
170
         * Intercala bandas en el buffer dependiendo de si hay que replicar o meter
171
         * bandas en negro. Esto tiene es valido para buffers con solo una banda ya que
172
         * el dibujado sobre Graphics debe ser R, G, B.
173
         * 
174
         * @param replicateBand false si no se replican bandas y las que no existen 
175
         * se ponen en negro y false si hay que dibujar la misma en R,G y B. Esto 
176
         * tiene sentido si el raster tiene solo 1 o 2 bandas.
177
         * @param renderBands array con las posiciones de renderizado. 
178
         *  A la hora de renderizar hay que tener en cuenta que solo se renderizan las 
179
         * tres primeras bandas del buffer por lo que solo se tienen en cuenta los tres primeros
180
         * elementos. Por ejemplo, el array {1, 0, 3} dibujar? sobre el Graphics las bandas 1,0 y 3 de un
181
         * raster de al menos 4 bandas.La notaci?n con -1 en alguna posici?n del vector solo tiene sentido
182
         * en la visualizaci?n pero no se puede as?gnar una banda del buffer a null.
183
         * Algunos ejemplos:
184
         * <P> 
185
         * {-1, 0, -1} Dibuja la banda 0 del raster en la G de la visualizaci?n.
186
         * Si replicateBand es true R = G = B sino R = B = 0
187
         * {1, 0, 3} La R = banda 1 del raster, G = 0 y B = 3
188
         * {0} La R = banda 0 del raster. Si replicateBand es true R = G = B sino G = B = 0
189
         * </P>
190
         */
191
        /*private void adaptBufferToRender(boolean replicateBand, int[] renderBands){
192
                byte[][] aux = null;
193
                if(rasterBuf.getBandCount() < 3){
194
                        for(int i = 0; i < renderBands.length; i++){
195
                                if( replicateBand && renderBands[i] == -1)
196
                                        rasterBuf.replicateBand(0, i);
197
                                if( !replicateBand && renderBands[i] == -1){
198
                                        if(aux == null)
199
                                                aux = rasterBuf.createByteBand(rasterBuf.getWidth(), rasterBuf.getHeight(), (byte)0);
200
                                        rasterBuf.addBandByte(i, aux);
201
                                }
202
                        }
203
                }
204
        }*/
205

    
206
        /**
207
         * Asigna al objeto GridTransparency la banda de transparencia si la tiene para
208
         * tenerla en cuenta en el renderizado.
209
         * @param renderBands Lista de bandas a renderizar
210
         * @param ts Objeto con las propiedades de transparencia del Grid.
211
         */
212
        /*private void assignTransparencyBand(int[] renderBands) {
213
                if(transparency != null){
214
                        for(int i = 0; i < transparency.getTransparencyBandNumberList().size(); i ++) {
215
                                for(int j = 0; j < renderBands.length; j ++) {
216
                                        if(renderBands[j] == ((Integer)transparency.getTransparencyBandNumberList().get(i)).intValue()){
217
                                                if(transparency.getBand() == null)
218
                                                        transparency.setBand(rasterBuf.getBandBuffer(renderBands[j]));
219
                                                else {
220
                                                        IBuffer outBuf = transparency.getBand().cloneBuffer();
221
                                                        transparency.mergeTransparencyBands(new IBuffer[]{transparency.getBand(), rasterBuf.getBandBuffer(renderBands[j])}, outBuf);
222
                                                }
223
                                        }
224
                                }
225
                        }
226
                }
227
        }*/
228

    
229
        private IBuffer convertToByte(IBuffer buf) {
230
                IBuffer b = RasterBuffer.getBuffer(IBuffer.TYPE_BYTE, buf.getWidth(), buf.getHeight(), buf.getBandCount(), true);
231
                if(buf.getDataType() == IBuffer.TYPE_SHORT) {
232
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
233
                                for (int row = 0; row < buf.getHeight(); row++)
234
                                        for (int col = 0; col < buf.getWidth(); col++)
235
                                                b.setElem(row, col, nBand, (byte)(buf.getElemShort(row, col, nBand) & 0xffff));
236
                }
237
                if(buf.getDataType() == IBuffer.TYPE_INT) {
238
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
239
                                for (int row = 0; row < buf.getHeight(); row++)
240
                                        for (int col = 0; col < buf.getWidth(); col++)
241
                                                b.setElem(row, col, nBand, (byte)(buf.getElemInt(row, col, nBand) & 0xffffffff));
242
                }
243
                if(buf.getDataType() == IBuffer.TYPE_FLOAT) {
244
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
245
                                for (int row = 0; row < buf.getHeight(); row++)
246
                                        for (int col = 0; col < buf.getWidth(); col++)
247
                                                b.setElem(row, col, nBand, (byte)(Math.round(buf.getElemFloat(row, col, nBand))));
248
                }
249
                if(buf.getDataType() == IBuffer.TYPE_DOUBLE) {
250
                        for (int nBand = 0; nBand < buf.getBandCount(); nBand++)
251
                                for (int row = 0; row < buf.getHeight(); row++)
252
                                        for (int col = 0; col < buf.getWidth(); col++)
253
                                                b.setElem(row, col, nBand, (byte)(Math.round(buf.getElemDouble(row, col, nBand))));
254
                }
255
                return b;
256
        }
257

    
258
        /**
259
         * Asigna el buffer a renderizar
260
         * @param b Buffer a renderizar
261
         */
262
        public void setBuffer(IBuffer b) {
263
                this.rasterBuf = b;
264
        }
265

    
266
        /**
267
         * Asigna la paleta asociada al grid
268
         * @param palette 
269
         */
270
        /*public void setPalette(GridPalette palette) {
271
                this.palette = palette;
272
        }*/
273

    
274
        /**
275
         * Asigna el objeto que contiene el estado de transparencia del grid
276
         * @param transparency
277
         */
278
        public void setTransparency(GridTransparency transparency) {
279
                this.transparency = transparency;
280
        }
281

    
282
        /**
283
         * Asigna el desplazamiento en pixeles desde la esquina superior izquierda. Si es null se considera que esta
284
         * funci?n la ha hecho el driver quedando desactivada en el renderizador. Si es as? no debe variar el resultado
285
         * en la visualizacion. 
286
         * Si Supersamplea el renderizador se cargar? una matriz de datos 1:1 por lo que se podr? aplicar un filtro 
287
         * a este buffer de datos leidos independientemente del zoom que tengamos.
288
         * @param step Desplazamiento
289
         */
290
        public void setStep(int[] step) {
291
                this.step = step;
292
        }
293

    
294
        /**
295
         * Asigna el ancho y el alto del BufferedImage. Esto es util para cuando hay supersampling
296
         * que el tama?o del objeto Image no coincide con el buffer con los datos raster.  
297
         * @param w Ancho
298
         * @param h Alto
299
         */
300
        public void setBufferSize(int w, int h) {
301
                this.width = w;
302
                this.height = h;
303
        }
304

    
305
        /**
306
         * Asigna el ancho y el alto en pixeles a dibujar. Esto es util para cuando hay supersampling
307
         * ya que necesitamos saber la relaci?n entre el ancho o alto del objeto image y en ancho o alto en pixels
308
         * del buffer. No vale la informaci?n contenida en rasterBuf (ni rasterBuf.getWidth ni rasterBuf.getHeight) 
309
         * ya que esta es entera y necesitamos el valor en double para mantener la precisi?n del calculo.  
310
         * @param w Ancho
311
         * @param h Alto
312
         */
313
        public void setPixelsToDrawSize(double w, double h) {
314
                this.nWidth = w;
315
                this.nHeight = h;
316
        }
317

    
318
}