package ip.ppm;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class WritePPM {
int width;
int height;
public static void doIt(
short r[][], short g[][], short b[][],
String fn) {
WritePPM wppm = new WritePPM(r.length, r[0].length);
try {
OutputStream os = new BufferedOutputStream(
new FileOutputStream(fn));
wppm.writeHeader(os);
wppm.writeImage(os, r, g, b);
os.flush();
os.close();
} catch (IOException e) {
System.out.println(e + " IOException");
}
}
public WritePPM(int w, int h) {
width = w;
height = h;
}
public void writeHeader(OutputStream os) {
writeString(os, "P6\n");
writeString(os, width + " " + height + "\n");
writeString(os, "255\n");
}
static void writeString(OutputStream out, String str) {
int len = str.length();
byte[] buf = new byte[len];
buf = str.getBytes();
try {
out.write(buf);
} catch (Exception e) {
System.out.println(e);
}
}
private void printDimensions(short r[][],
String nm) {
System.out.println(
nm + ".length =" + r.length + " "
+ nm + "[0].length =" + r[0].length);
}
public void writeImage(OutputStream os,
short r[][],
short g[][],
short b[][]) {
int j = 0;
width = r.length;
height = r[0].length;
byte[] ppmPixels = new byte[width * height * 3];
try {
for (int col = 0; col < height; col++) {
for (int row = 0; row < width; row++) {
ppmPixels[j++] = (byte) r[row][col];
ppmPixels[j++] = (byte) g[row][col];
ppmPixels[j++] = (byte) b[row][col];
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
os.write(ppmPixels);
} catch (Exception e) {
System.out.println(e + " os.write");
}
}
}