/Users/lyon/j4p/src/ip/ppm/WritePPM.java
|
1 /**
2 * WritePPM is a class that takes an Image and saves it to
3 * a PPM format file.
4 *
5 * Victor Silva (victor@bridgeport.edu).
6 * Modified by D.L. (lyon@DocJava.com)
7 *
8 */
9 package ip.ppm;
10
11 import java.io.BufferedOutputStream;
12 import java.io.FileOutputStream;
13 import java.io.IOException;
14 import java.io.OutputStream;
15
16 public class WritePPM {
17 int width;
18 int height;
19
20 public static void doIt(
21 short r[][], short g[][], short b[][],
22 String fn) {
23 WritePPM wppm = new WritePPM(r.length, r[0].length);
24 try {
25 OutputStream os = new BufferedOutputStream(
26 new FileOutputStream(fn));
27 wppm.writeHeader(os);
28 //System.out.println("Header OK");
29 wppm.writeImage(os, r, g, b);
30 //System.out.println("Image written");
31 os.flush();
32 os.close();
33 } catch (IOException e) {
34 System.out.println(e + " IOException");
35 }
36 }
37
38
39 public WritePPM(int w, int h) {
40 width = w;
41 height = h;
42 }
43
44
45 public void writeHeader(OutputStream os) {
46 writeString(os, "P6\n");
47 writeString(os, width + " " + height + "\n");
48
49 // Write the maximum value of each color.
50 // i.e. r,g,b all vary between 0 and 255.
51 writeString(os, "255\n");
52 }
53
54 static void writeString(OutputStream out, String str) {
55 int len = str.length();
56 byte[] buf = new byte[len];
57 // now deprecated
58 // str.getBytes( 0, len, buf, 0 );
59 // use the following instead:
60 buf = str.getBytes();
61 try {
62 out.write(buf);
63 } catch (Exception e) {
64 System.out.println(e);
65 }
66 }
67
68 private void printDimensions(short r[][],
69 String nm) {
70 System.out.println(
71 nm + ".length =" + r.length + " "
72 + nm + "[0].length =" + r[0].length);
73
74 }
75
76 public void writeImage(OutputStream os,
77 short r[][],
78 short g[][],
79 short b[][]) {
80 int j = 0;
81 width = r.length;
82 height = r[0].length;
83 byte[] ppmPixels = new byte[width * height * 3];
84 //System.os.println("Writing image "+width+"x"+height);
85 // yowsa!!
86 // tuff error to spot!
87 // for ( int col = 0; col < width ; ++col ) { is wrong!!
88 // for ( int col = 0; col < height ; col++ ) { is correct!
89 try {
90 for (int col = 0; col < height; col++) {
91 for (int row = 0; row < width; row++) {
92 ppmPixels[j++] = (byte) r[row][col];
93 ppmPixels[j++] = (byte) g[row][col];
94 ppmPixels[j++] = (byte) b[row][col];
95 }
96 }
97 } catch (Exception e) {
98 e.printStackTrace();
99 }
100 // Write ppm file all at once.
101 try {
102 os.write(ppmPixels);
103 } catch (Exception e) {
104 System.out.println(e + " os.write");
105 }
106 }
107 }
108