001    //$HeadURL: svn+ssh://rbezema@svn.wald.intevation.org/deegree/base/tags/2.1/src/org/deegree/model/coverage/grid/ByteGridCoverage.java $
002    /*----------------    FILE HEADER  ------------------------------------------
003    
004     This file is part of deegree.
005     Copyright (C) 2001-2006 by:
006     EXSE, Department of Geography, University of Bonn
007     http://www.giub.uni-bonn.de/deegree/
008     lat/lon GmbH
009     http://www.lat-lon.de
010    
011     This library is free software; you can redistribute it and/or
012     modify it under the terms of the GNU Lesser General Public
013     License as published by the Free Software Foundation; either
014     version 2.1 of the License, or (at your option) any later version.
015    
016     This library is distributed in the hope that it will be useful,
017     but WITHOUT ANY WARRANTY; without even the implied warranty of
018     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
019     Lesser General Public License for more details.
020    
021     You should have received a copy of the GNU Lesser General Public
022     License along with this library; if not, write to the Free Software
023     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
024    
025     Contact:
026    
027     Andreas Poth
028     lat/lon GmbH
029     Aennchenstr. 19
030     53115 Bonn
031     Germany
032     E-Mail: poth@lat-lon.de
033    
034     Klaus Greve
035     Department of Geography
036     University of Bonn
037     Meckenheimer Allee 166
038     53115 Bonn
039     Germany
040     E-Mail: klaus.greve@uni-bonn.de
041    
042     
043     ---------------------------------------------------------------------------*/
044    package org.deegree.model.coverage.grid;
045    
046    import java.awt.Rectangle;
047    import java.awt.image.BandedSampleModel;
048    import java.awt.image.BufferedImage;
049    import java.awt.image.DataBuffer;
050    import java.awt.image.DataBufferByte;
051    import java.awt.image.Raster;
052    import java.awt.image.SampleModel;
053    import java.awt.image.renderable.RenderableImage;
054    
055    import org.deegree.model.spatialschema.Envelope;
056    import org.deegree.model.spatialschema.GeometryFactory;
057    import org.deegree.ogcwebservices.wcs.describecoverage.CoverageOffering;
058    import org.opengis.pt.PT_Envelope;
059    
060    /**
061     * GridCoverage implementation for holding grids stored in a raw byte
062     * matrix (byte[][]) or in a set of <tt>ByteGridCoverage</tt>s
063     *
064     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
065     * @author last edited by: $Author: apoth $
066     *
067     * @version $Revision: 7842 $, $Date: 2007-07-25 09:44:14 +0200 (Mi, 25 Jul 2007) $
068     */
069    public class ByteGridCoverage extends AbstractGridCoverage {
070    
071        private static final long serialVersionUID = 5612511572056707069L;
072        
073        private byte[][][] data = null;    
074        
075                    
076        /**
077         * @param coverageOffering
078         * @param envelope 
079         * @param data 
080         */
081        public ByteGridCoverage(CoverageOffering coverageOffering, Envelope envelope,
082                                byte[][][] data) {
083            this(coverageOffering, envelope, false, data);
084        }
085    
086        /**
087         * @param coverageOffering
088         * @param envelope 
089         * @param isEditable
090         * @param data 
091         */
092        public ByteGridCoverage(CoverageOffering coverageOffering, Envelope envelope, 
093                                 boolean isEditable, byte[][][] data) {
094            super(coverageOffering, envelope, isEditable);
095            this.data = data;       
096        }
097    
098        /**
099         * @param coverageOffering
100         * @param envelope 
101         * @param sources
102         */
103        public ByteGridCoverage(CoverageOffering coverageOffering, Envelope envelope,
104                                 ByteGridCoverage[] sources) {
105            super(coverageOffering, envelope, sources);
106        } 
107        
108        /**
109         * The number of sample dimensions in the coverage.
110         * For grid coverages, a sample dimension is a band.
111         *
112         * @return The number of sample dimensions in the coverage.
113         * @UML mandatory numSampleDimensions
114         */
115        public int getNumSampleDimensions() {
116            if ( data != null ) {
117                    return data.length;
118            }
119            return sources[0].getNumSampleDimensions();
120        } 
121        
122        /**
123         * Returns 2D view of this coverage as a renderable image.
124         * This optional operation allows interoperability with
125         * <A HREF="http://java.sun.com/products/java-media/2D/">Java2D</A>.
126         * If this coverage is a {@link "org.opengis.coverage.grid.GridCoverage"} backed
127         * by a {@link java.awt.image.RenderedImage}, the underlying image can be obtained
128         * with:
129         *
130         * <code>getRenderableImage(0,1).{@linkplain RenderableImage#createDefaultRendering()
131         * createDefaultRendering()}</code>
132         *
133         * @param  xAxis Dimension to use for the <var>x</var> axis.
134         * @param  yAxis Dimension to use for the <var>y</var> axis.
135         * @return A 2D view of this coverage as a renderable image.
136         * @throws UnsupportedOperationException if this optional operation is not supported.
137         * @throws IndexOutOfBoundsException if <code>xAxis</code> or 
138         *         <code>yAxis</code> is out of bounds.
139         */
140        public RenderableImage getRenderableImage(int xAxis, int yAxis)
141                throws UnsupportedOperationException, IndexOutOfBoundsException {
142            if ( data != null ) {
143                
144                return null;
145            } 
146            //TODO if multi images -> sources.length > 0
147            return null;
148        } 
149        
150        /**
151         * this is a deegree convenience method which returns the source image
152         * of an <tt>ImageGridCoverage</tt>. In procipal the same can be done 
153         * with the getRenderableImage(int xAxis, int yAxis) method. but creating
154         * a  <tt>RenderableImage</tt> image is very slow.
155         * I xAxis or yAxis <= 0 then the size of the returned image will be 
156         * calculated from the source images of the coverage.
157         * @param  xAxis Dimension to use for the <var>x</var> axis.
158         * @param  yAxis Dimension to use for the <var>y</var> axis.
159         * @return the source image of an <tt>ImageGridCoverage</tt>.
160         */
161        public BufferedImage getAsImage(int xAxis, int yAxis) {
162            
163            if ( xAxis <= 0 || yAxis <= 0 ) {
164                // get default size if passed target size is <= 0
165                Rectangle rect = calculateOriginalSize();
166                xAxis = rect.width;
167                yAxis = rect.height;
168            }        
169            BufferedImage bi = createBufferedImage( xAxis, yAxis );                
170            if ( data != null ) {
171                    bi = createBufferedImage( data[0][0].length, data[0].length );
172                    // total number of fields for one band; it is assumed that each
173                    // band has the same number of fiels
174                    int numOfFields = data[0].length*data[0][0].length;
175                byte[][] bb = new byte[data.length][];            
176                for (int z = 0; z < data.length; z++) {
177                    bb[z] = new byte[ numOfFields ];
178                }
179                    int c = 0;              
180                    for (int i = 0; i < data[0].length; i++) {
181                            for (int j = 0; j < data[0][i].length; j++) {
182                                    for (int z = 0; z < data.length; z++) {
183                                            bb[z][c] = data[z][i][j];
184                                    }
185                                    c++;
186                            }
187                }
188                DataBuffer db = new DataBufferByte( bb, numOfFields );
189                SampleModel sm = 
190                    new BandedSampleModel(DataBuffer.TYPE_BYTE, data[0][0].length,
191                                                  data[0].length, data.length);
192                Raster raster = Raster.createWritableRaster( sm, db, null );                    
193                bi.setData(raster);
194            } else {
195                // it's a complex ByteGridCoverage made up of different
196                // source coverages
197                for (int i = 0; i < sources.length; i++) {            
198                    PT_Envelope env = sources[i].getEnvelope();
199                    Envelope sourceEnv = 
200                        GeometryFactory.createEnvelope( env.minCP.ord[0], env.minCP.ord[1],
201                                                        env.maxCP.ord[0], env.maxCP.ord[1], 
202                                                        null);
203                    BufferedImage sourceImg = ((AbstractGridCoverage)sources[i]).getAsImage(-1,-1);
204                    env = this.getEnvelope();
205                    Envelope targetEnv = 
206                        GeometryFactory.createEnvelope( env.minCP.ord[0], env.minCP.ord[1],
207                                                        env.maxCP.ord[0], env.maxCP.ord[1], 
208                                                        null);
209                    bi = paintImage( bi, targetEnv, sourceImg, sourceEnv );
210                }
211            }        
212            
213            return bi;
214        }
215        
216        private BufferedImage createBufferedImage(int xAxis, int yAxis) {
217            int sampleDim = getNumSampleDimensions();
218            switch (sampleDim) {
219                    case 1: return new BufferedImage( xAxis, yAxis, BufferedImage.TYPE_BYTE_GRAY);
220                    case 3: return new BufferedImage( xAxis, yAxis, BufferedImage.TYPE_INT_RGB);
221                    default: return new BufferedImage( xAxis, yAxis, BufferedImage.TYPE_INT_ARGB);
222            }
223        }
224        
225        /**
226         * calculates the original size of a gridcoverage based on its resolution and the envelope(s) of
227         * its source(s).
228         * 
229         * @return
230         */
231        private Rectangle calculateOriginalSize() {
232            if ( data != null ) {
233                return new Rectangle( data[0].length, data.length );
234            }
235            BufferedImage bi = ((ImageGridCoverage)sources[0]).getAsImage(-1,-1);
236            PT_Envelope env = sources[0].getEnvelope();        
237            double dx =  (env.maxCP.ord[0]-env.minCP.ord[0])/bi.getWidth();
238            double dy =  (env.maxCP.ord[1]-env.minCP.ord[1])/bi.getHeight();
239            env = this.getEnvelope();
240            int w = (int)Math.round( (env.maxCP.ord[0]-env.minCP.ord[0])/dx );
241            int h = (int)Math.round( (env.maxCP.ord[1]-env.minCP.ord[1])/dy );
242            return new Rectangle( w, h );
243        }
244    }