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.io.IOException;
20 import java.io.InputStream;
21
22 import org.apache.commons.imaging.ImageFormat;
23 import org.apache.commons.imaging.ImageInfo;
24 import org.apache.commons.imaging.ImagingException;
25 import org.apache.commons.imaging.common.ImageBuilder;
26
27 abstract class AbstractFileInfo {
28
29 static int readSample(final InputStream is, final int bytesPerSample) throws IOException {
30 int sample = 0;
31 for (int i = 0; i < bytesPerSample; i++) {
32 final int nextByte = is.read();
33 if (nextByte < 0) {
34 throw new ImagingException("PNM: Unexpected EOF");
35 }
36 sample <<= 8;
37 sample |= nextByte;
38 }
39 return sample;
40 }
41
42 static int scaleSample(int sample, final float scale, final int max) throws ImagingException {
43 if (sample < 0) {
44
45 throw new ImagingException("Negative pixel values are invalid in PNM files");
46 }
47 if (sample > max) {
48
49 sample = 0;
50 }
51 return (int) (sample * scale / max + 0.5f);
52 }
53
54 final int width;
55
56 final int height;
57
58 final boolean rawBits;
59
60 AbstractFileInfo(final int width, final int height, final boolean rawBits) {
61 this.width = width;
62 this.height = height;
63 this.rawBits = rawBits;
64 }
65
66 abstract int getBitDepth();
67
68 abstract ImageInfo.ColorType getColorType();
69
70 abstract ImageFormat getImageType();
71
72 abstract String getImageTypeDescription();
73
74 abstract String getMimeType();
75
76 abstract int getNumComponents();
77
78 abstract int getRgb(InputStream is) throws IOException;
79
80 abstract int getRgb(WhiteSpaceReader wsr) throws IOException;
81
82 abstract boolean hasAlpha();
83
84 void newline() {
85
86 }
87
88 void readImage(final ImageBuilder imageBuilder, final InputStream is) throws IOException {
89
90
91
92
93
94
95 if (!rawBits) {
96 final WhiteSpaceReader wsr = new WhiteSpaceReader(is);
97
98 for (int y = 0; y < height; y++) {
99 for (int x = 0; x < width; x++) {
100 final int rgb = getRgb(wsr);
101
102 imageBuilder.setRgb(x, y, rgb);
103
104 }
105 newline();
106 }
107 } else {
108 for (int y = 0; y < height; y++) {
109
110 for (int x = 0; x < width; x++) {
111 final int rgb = getRgb(is);
112 imageBuilder.setRgb(x, y, rgb);
113
114 }
115 newline();
116 }
117 }
118
119
120
121
122
123
124 }
125 }