1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.imaging.formats.pnm;
18
19 import java.awt.image.BufferedImage;
20 import java.io.IOException;
21 import java.io.OutputStream;
22 import java.nio.charset.StandardCharsets;
23
24 import org.apache.commons.imaging.ImagingException;
25
26 final class PbmWriter implements PnmWriter {
27
28 private final boolean rawBits;
29
30 PbmWriter(final boolean rawBits) {
31 this.rawBits = rawBits;
32 }
33
34 @Override
35 public void writeImage(final BufferedImage src, final OutputStream os, final PnmImagingParameters params) throws ImagingException, IOException {
36 os.write(PnmConstants.PNM_PREFIX_BYTE);
37 os.write(rawBits ? PnmConstants.PBM_RAW_CODE : PnmConstants.PBM_TEXT_CODE);
38 os.write(PnmConstants.PNM_SEPARATOR);
39
40 final int width = src.getWidth();
41 final int height = src.getHeight();
42
43 os.write(Integer.toString(width).getBytes(StandardCharsets.US_ASCII));
44 os.write(PnmConstants.PNM_SEPARATOR);
45
46 os.write(Integer.toString(height).getBytes(StandardCharsets.US_ASCII));
47 os.write(PnmConstants.PNM_NEWLINE);
48
49 int bitcache = 0;
50 int bitsInCache = 0;
51
52 for (int y = 0; y < height; y++) {
53 for (int x = 0; x < width; x++) {
54 final int argb = src.getRGB(x, y);
55 final int red = 0xff & argb >> 16;
56 final int green = 0xff & argb >> 8;
57 final int blue = 0xff & argb >> 0;
58 int sample = (red + green + blue) / 3;
59 if (sample > 127) {
60 sample = 0;
61 } else {
62 sample = 1;
63 }
64
65 if (rawBits) {
66 bitcache = bitcache << 1 | 0x1 & sample;
67 bitsInCache++;
68
69 if (bitsInCache >= 8) {
70 os.write((byte) bitcache);
71 bitcache = 0;
72 bitsInCache = 0;
73 }
74 } else {
75 os.write(Integer.toString(sample).getBytes(StandardCharsets.US_ASCII));
76
77
78 os.write(PnmConstants.PNM_SEPARATOR);
79 }
80 }
81
82 if (rawBits && bitsInCache > 0) {
83 bitcache = bitcache << 8 - bitsInCache;
84 os.write((byte) bitcache);
85 bitcache = 0;
86 bitsInCache = 0;
87 }
88 }
89 }
90 }