1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.imaging.formats.pnm;
19
20 import java.awt.image.BufferedImage;
21 import java.io.IOException;
22 import java.io.OutputStream;
23 import java.nio.charset.StandardCharsets;
24
25 import org.apache.commons.imaging.ImagingException;
26
27 final class PamWriter implements PnmWriter {
28
29 @Override
30 public void writeImage(final BufferedImage src, final OutputStream os, final PnmImagingParameters params) throws ImagingException, IOException {
31
32 os.write(PnmConstants.PNM_PREFIX_BYTE);
33 os.write(PnmConstants.PAM_RAW_CODE);
34 os.write(PnmConstants.PNM_NEWLINE);
35
36 final int width = src.getWidth();
37 final int height = src.getHeight();
38
39 os.write(("WIDTH " + width).getBytes(StandardCharsets.US_ASCII));
40 os.write(PnmConstants.PNM_NEWLINE);
41
42 os.write(("HEIGHT " + height).getBytes(StandardCharsets.US_ASCII));
43 os.write(PnmConstants.PNM_NEWLINE);
44
45 os.write("DEPTH 4".getBytes(StandardCharsets.US_ASCII));
46 os.write(PnmConstants.PNM_NEWLINE);
47
48 os.write("MAXVAL 255".getBytes(StandardCharsets.US_ASCII));
49 os.write(PnmConstants.PNM_NEWLINE);
50
51 os.write("TUPLTYPE RGB_ALPHA".getBytes(StandardCharsets.US_ASCII));
52 os.write(PnmConstants.PNM_NEWLINE);
53
54 os.write("ENDHDR".getBytes(StandardCharsets.US_ASCII));
55 os.write(PnmConstants.PNM_NEWLINE);
56
57 for (int y = 0; y < height; y++) {
58 for (int x = 0; x < width; x++) {
59 final int argb = src.getRGB(x, y);
60 final int alpha = 0xff & argb >> 24;
61 final int red = 0xff & argb >> 16;
62 final int green = 0xff & argb >> 8;
63 final int blue = 0xff & argb >> 0;
64
65 os.write((byte) red);
66 os.write((byte) green);
67 os.write((byte) blue);
68 os.write((byte) alpha);
69 }
70 }
71 }
72 }