Statistics
| Revision:

root / trunk / extensions / extGeoreferencing / src / org / gvsig / georeferencing / utils / GeoUtils.java @ 6214

History | View | Annotate | Download (10.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.georeferencing.utils;
20

    
21
import java.awt.geom.Point2D;
22
import java.awt.geom.Rectangle2D;
23
import java.io.BufferedReader;
24
import java.io.File;
25
import java.io.FileInputStream;
26
import java.io.FileNotFoundException;
27
import java.io.FileOutputStream;
28
import java.io.FileReader;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32

    
33
import com.iver.cit.gvsig.fmap.ViewPort;
34

    
35
public class GeoUtils {
36
        public static double INCHESMTR = 39.73007874D;
37
        public static double INCHESCM = 0.3973007874D;
38
        public static double INCHESMM = 0.03973007874D;
39
        public static double MTRSINCH = 0.0254D;
40
        public static double MMSINCH = 25.4D;
41
        public static double CMSINCH = 2.54D;
42
        
43
        
44
        /**
45
     * Recorta el n?mero de decimales a n del n?mero pasado por par?metro
46
     * @param num Valor a recortar el n?mero de decimales
47
     * @param n N?mero de decimales a recortar
48
     * @return N?mero recortado
49
     */
50
    public static double tailDecimals(double num, int n){
51
            long m = (long)Math.pow(10, n);
52
        num *= m;
53
        long aux = ((long)num);
54
        num = (double)((double)aux / (double)m);
55
        return num;
56
    }
57
    
58
    /**
59
     * Recorta el n?mero de decimales a n del n?mero pasado por par?metro
60
     * @param num Valor a recortar el n?mero de decimales
61
     * @param n N?mero de decimales a recortar
62
     * @return N?mero recortado
63
     */
64
    public static String tailDecimals(String num, int n){
65
            int index = num.indexOf(".");
66
            if(index != -1){
67
                    try{
68
                            num = num.substring(0, index + n);
69
                    }catch(IndexOutOfBoundsException e){
70
                            //No hacemos nada pq retornar? num
71
                    }
72
            }
73
            return num;
74
    }
75
    
76
        /**
77
         * Convierte pixels en milimetros dependiendo del los puntos por pulgada
78
         * @param pixels N?mero de pixels
79
         * @param ppp Puntos por pulgada
80
         * @return N?mero de milimetros
81
         */
82
        public static double convertPixelsToMms(int pixels, int ppp){
83
                return convertPixelsToInches(pixels, ppp) * MMSINCH;
84
        }
85
        
86
        /**
87
         * Convierte pixels en centimetros dependiendo del los metros por pixel
88
         * @param pixels N?mero de pixels
89
         * @param mtsPixel Metros por pixel
90
         * @return N?mero de centimetros
91
         */
92
        public static double convertPixelsToCms(int pixels, int ppp){
93
                return convertPixelsToInches(pixels, ppp) * CMSINCH;
94
        }
95
        
96
        /**
97
         * Convierte pixels en metros dependiendo del los metros por pixel
98
         * @param pixels N?mero de pixels
99
         * @param mtsPixel Metros por pixel
100
         * @return N?mero de metros
101
         */
102
        public static double convertPixelsToMts(int pixels, int ppp){
103
                return convertPixelsToInches(pixels, ppp) * MTRSINCH;
104
        }
105
        
106
        /**
107
         * Convierte pixels en pulgadas dependiendo del los metros por pixel
108
         * @param pixels N?mero de pixels
109
         * @param mtsPixel Metros por pixel
110
         * @return N?mero de pulgadas
111
         */
112
        public static double convertPixelsToInches(int pixels, int ppp){
113
                return (double)((double)pixels / (double)ppp);
114
        }
115
        
116
        /**
117
         * Convierte metros en pixels dependiendo de los puntos por pulgada
118
         * @param mts N?mero de metros
119
         * @param ppp Puntos por pulgada
120
         * @return N?mero de pixeles
121
         */
122
        public static int convertMtsToPixels(double mts, int ppp){
123
                return (int)(mts * GeoUtils.INCHESMTR * ppp);
124
        }
125
        
126
        /**
127
         * Convierte pulgadas en pixels dependiendo de los puntos por pulgada
128
         * @param mts N?mero de pulgadas
129
         * @param ppp Puntos por pulgada
130
         * @return N?mero de pixeles
131
         */
132
        public static int convertInchesToPixels(double inches, int ppp){
133
                return (int)(inches * ppp);
134
        }
135
        
136
        /**
137
         * Convierte centimetros en pixels dependiendo de los puntos por pulgada
138
         * @param mts N?mero de centmetros
139
         * @param ppp Puntos por pulgada
140
         * @return N?mero de pixeles
141
         */
142
        public static int convertCmsToPixels(double cms, int ppp){
143
                return (int)(cms * GeoUtils.INCHESCM * ppp);
144
        }
145
        
146
        /**
147
         * Convierte milimetros en pixels dependiendo de los puntos por pulgada
148
         * @param mts N?mero de milimetros
149
         * @param ppp Puntos por pulgada
150
         * @return N?mero de pixeles
151
         */
152
        public static int convertMmsToPixels(double mms, int ppp){
153
                return (int)(mms * GeoUtils.INCHESMM * ppp);
154
        }
155
        
156
        /**
157
         * Devuelve la traspuesta de una matriz
158
         * @param M Matriz
159
         * @param m N?mero de filas
160
         * @param n N?mero de columnas
161
         * @return Matriz traspuesta
162
         */
163
        public static double[][] transpose(double[][] M, int m, int n){
164
          double[][]        a = new double[n][m];
165
          int                        i, j;
166
        
167
          for (i = 0; i < n; i++)
168
            for (j = 0; j < m; j++)
169
              a[i][j] = M[j][i];
170
          return a;
171
        }
172
        
173
        /**
174
         * Producto de matrices (AxB)
175
         * @param a        Matriz A
176
         * @param b Matriz B
177
         * @param M 
178
         * @param N        
179
         * @param O 
180
         * @return
181
         */
182
        public static double[][] multmatrix(double[][] a, double[][] b, int M, int N, int O){
183
          double[][]        c = new double[M][O]; 
184
          double                sum;
185
          int                        i, j, k;
186
          
187
          for (i = 0; i < M; i++) {
188
            for (j = 0; j < O; j++) {
189
              sum = 0;
190
              for (k = 0; k < N; k++)
191
                sum += b[k][j] * a[i][k];
192
              c[i][j] = sum;
193
            }
194
          }
195
          return (c);
196
        }
197
        
198
    /**
199
     * Calcula el zoom dependiendo del factor de escala pasado por
200
     * par?metro.
201
     */
202
    public static ViewPort calcZoom(ViewPort vp, double factor){
203
            ViewPort viewPortBlock = new ViewPort(vp.getProjection());
204
                viewPortBlock.setExtent(vp.getExtent());
205
                viewPortBlock.setImageSize(vp.getImageSize());        
206
                viewPortBlock.setScale();
207
                
208
            Rectangle2D.Double r = new Rectangle2D.Double();
209
                double nuevoX = (vp.getExtent().getCenterX()) - ((vp.getExtent().getWidth() * factor) / 2.0);
210
                double nuevoY = (vp.getExtent().getCenterY()) - ((vp.getExtent().getHeight() * factor) / 2.0);
211
                r.x = nuevoX;
212
                r.y = nuevoY;
213
                r.width = viewPortBlock.getExtent().getWidth() * factor;
214
                r.height = viewPortBlock.getExtent().getHeight() * factor;
215
                viewPortBlock.setExtent(r);
216
                viewPortBlock.setScale();
217
                
218
                return viewPortBlock;
219
        }
220
    
221
    /**
222
     * Desplaza el extent al nuevo centro 
223
     * @param pto
224
     */
225
    public static ViewPort shiftExtent(Point2D oldCenter, Point2D newCenter, ViewPort vp){
226
            double difX = oldCenter.getX() - newCenter.getX();
227
            double difY = oldCenter.getY() - newCenter.getY();
228
            
229
            ViewPort viewPortBlock = new ViewPort(vp.getProjection());
230
            double minX = vp.getExtent().getMinX() - difX;
231
            double minY = vp.getExtent().getMinY() - difY;
232
            Rectangle2D ex = new Rectangle2D.Double(minX, minY, vp.getExtent().getWidth(), vp.getExtent().getHeight());
233
                viewPortBlock.setExtent(ex);
234
                viewPortBlock.setImageSize(vp.getImageSize());        
235
                viewPortBlock.setScale();
236
                
237
                return viewPortBlock;
238
    }
239
    
240
    /**
241
     * Hace una copia de seguridad sobre el fichero que le pasamos por par?metro.
242
     * El fichero de copia se llama como el original pero acabado en ~. Si ya existiese
243
     * un fichero nombrado as? se nombraria como filename.rmf~1, filename.rmf~2, y as?
244
     * sucesivamente.
245
     * @param fName Nombre del fichero que se quiere hacer un backup.
246
     */
247
    public static String fileBackup(String fName){ 
248
            File inFile = new File(fName);
249
            if(!inFile.exists())
250
                    return null;
251
            
252
            File backupFile = new File(fName +"~");
253
            int nBackupFile = 1;
254
            while(backupFile.exists()){
255
                    backupFile = new File(fName + "~"+nBackupFile);
256
                    nBackupFile ++;
257
            }
258
                        
259
            try{
260
                    InputStream in = new FileInputStream(inFile);
261
                    OutputStream out = new FileOutputStream(backupFile);
262
        
263
                    byte[] buf = new byte[1024];
264
                    int len;
265
                    while ((len = in.read(buf)) > 0) 
266
                            out.write(buf, 0, len);
267
                     
268
                    in.close();
269
                    out.close();
270
            }catch(FileNotFoundException exc){
271
                    System.err.print("RMF Backup: File not found, "+fName);
272
                    return null;
273
            }catch(IOException exc){
274
                    System.err.print("RMF Backup: IOException, "+fName);
275
                    return null;
276
            }
277
            return backupFile.getAbsolutePath();
278
    }
279
    
280
    /**
281
     * A partir de una extensi?n de fichero devuelve la extensi?n del fichero 
282
     * WorldFile que le corresponde.
283
     * @param fileExtension Extensi?n del fichero
284
     * @return Extensi?n del fichero de georreferenciaci?n
285
     */
286
    public static String getWorldFileExtension(String ext){
287
            String extWorldFile = ".wld";
288
            if(ext.equals("tif") || ext.equals("tiff"))
289
                    extWorldFile = ".tfw";
290
            if(ext.equals("jpeg") || ext.equals("jpg"))
291
                    extWorldFile = ".jgw";
292
            if(ext.equals("gif"))
293
                    extWorldFile = ".gfw";
294
            if(ext.equals("png"))
295
                    extWorldFile = ".pgw";
296
            return extWorldFile;
297
    }
298
    
299
    /**
300
     * A partir de un nombre de fichero devuelve la extensi?n del fichero 
301
     * WorldFile que le corresponde.
302
     * @param file Nombre del fichero
303
     * @return Extensi?n del fichero de georreferenciaci?n
304
     */
305
    public static String getWorldFileExtensionFromFileName(String file){
306
            String ext = file.substring(file.lastIndexOf(".") + 1).toLowerCase();
307
            return GeoUtils.getWorldFileExtension(ext);
308
    }
309
    
310
        /**
311
         * Obtiene la codificaci?n del fichero XML
312
         * @param file Nombre del fichero XML
313
         * @return Codificaci?n
314
         */
315
        public static String readFileEncoding(String file){
316
                FileReader fr;
317
                String encoding = null;
318
                try
319
            {
320
                        fr = new FileReader(file);
321
                    BufferedReader br = new BufferedReader(fr);
322
                    char[] buffer = new char[100];
323
                    br.read(buffer);
324
                    StringBuffer st = new StringBuffer(new String(buffer));
325
                    String searchText = "encoding=\"";
326
                    int index = st.indexOf(searchText);
327
                    if (index>-1) {
328
                            st.delete(0, index+searchText.length());
329
                            encoding = st.substring(0, st.indexOf("\""));
330
                    }
331
                    fr.close();
332
            } catch(FileNotFoundException ex)        {
333
                    ex.printStackTrace();
334
            } catch (IOException e) {
335
                        e.printStackTrace();
336
                }
337
            return encoding;
338
        }
339
}