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