Initial revision
[openjpeg.git] / j2kviewer / src / PgmImage.java
1 import java.awt.*;
2 import java.awt.image.*;
3 import java.net.*;
4 import java.io.*;
5 import java.util.regex.*;
6
7 class PgmImage extends Component
8 {
9   private Socket s;
10   private BufferedReader in;
11   private int x, y;
12   
13   PgmImage()
14   {
15   }
16   
17   private String read()
18   {
19     try { return in.readLine(); }
20     catch (IOException e) {
21       e.printStackTrace();
22       return null;
23     }
24   }
25   
26   public Image open(String filename)
27   {
28     String  str;
29     Pattern pat;
30     Matcher mat;
31     int bytes, width, height, depth;
32     FileInputStream fis;
33     
34     try {
35       in  = new BufferedReader(
36               new InputStreamReader(
37                 fis = new FileInputStream(
38                   new File(filename))));
39
40       pat = Pattern.compile("^P5$");
41       mat = pat.matcher(str = read());
42       mat.matches();
43       pat = Pattern.compile("^(\\d+) (\\d+)$");
44       mat = pat.matcher(str = read());
45       mat.matches();
46       x = new Integer(mat.group(1)).intValue();
47       y = new Integer(mat.group(2)).intValue();
48       width  = x;
49       height = y;
50       depth  = 1;
51       pat = Pattern.compile("^255$");
52       mat = pat.matcher(str = read());
53       mat.matches();
54       bytes = x*y;
55       char[] buf = new char[bytes];
56       int r, offset = 0;
57       while (bytes > 0) {
58         try { r = in.read(buf, offset, bytes); offset += r; bytes -= r; }
59         catch (IOException e) { e.printStackTrace(); }
60       }
61       int[] buf2 = new int[buf.length];
62       if (depth == 3) {
63         for (int i = 0; i < buf.length/3; ++i)
64           buf2[i] = 0xFF << 24 | buf[3*i] << 16 | buf[3*i+1] << 8 | buf[3*i+2];
65       } else {
66         for (int i = 0; i < buf.length; ++i)
67           buf2[i] = 0xFF << 24 | buf[i] << 16 | buf[i] << 8 | buf[i];
68       }
69       fis.close();
70       return createImage(new MemoryImageSource(width, height, buf2, 0, width));
71     } catch (IOException e) { e.printStackTrace(); }
72     return null;
73   }
74
75   public void close()
76   {
77   }
78   
79   public boolean bye()
80   {
81     return true;
82   }
83   
84   public int getXOffset()
85   {
86     return x;
87   }
88   
89   public int getYOffset()
90   {
91     return y;
92   }
93 }