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.ImageFormats;
24 import org.apache.commons.imaging.ImageInfo;
25 import org.apache.commons.imaging.ImagingException;
26
27 final class PgmFileInfo extends AbstractFileInfo {
28 private final int max;
29 private final float scale;
30 private final int bytesPerSample;
31
32 PgmFileInfo(final int width, final int height, final boolean rawbits, final int max) throws ImagingException {
33 super(width, height, rawbits);
34 if (max <= 0) {
35 throw new ImagingException("PGM maxVal " + max + " is out of range [1;65535]");
36 }
37 if (max <= 255) {
38 scale = 255f;
39 bytesPerSample = 1;
40 } else if (max <= 65535) {
41 scale = 65535f;
42 bytesPerSample = 2;
43 } else {
44 throw new ImagingException("PGM maxVal " + max + " is out of range [1;65535]");
45 }
46 this.max = max;
47 }
48
49 @Override
50 public int getBitDepth() {
51 return max;
52 }
53
54 @Override
55 public ImageInfo.ColorType getColorType() {
56 return ImageInfo.ColorType.GRAYSCALE;
57 }
58
59 @Override
60 public ImageFormat getImageType() {
61 return ImageFormats.PGM;
62 }
63
64 @Override
65 public String getImageTypeDescription() {
66 return "PGM: portable graymap file format";
67 }
68
69 @Override
70 public String getMimeType() {
71 return "image/x-portable-graymap";
72 }
73
74 @Override
75 public int getNumComponents() {
76 return 1;
77 }
78
79 @Override
80 public int getRgb(final InputStream is) throws IOException {
81 int sample = readSample(is, bytesPerSample);
82
83 sample = scaleSample(sample, scale, max);
84
85 final int alpha = 0xff;
86
87 return (0xff & alpha) << 24 | (0xff & sample) << 16 | (0xff & sample) << 8 | (0xff & sample) << 0;
88 }
89
90 @Override
91 public int getRgb(final WhiteSpaceReader wsr) throws IOException {
92 int sample = Integer.parseInt(wsr.readtoWhiteSpace());
93
94 sample = scaleSample(sample, scale, max);
95
96 final int alpha = 0xff;
97
98 return (0xff & alpha) << 24 | (0xff & sample) << 16 | (0xff & sample) << 8 | (0xff & sample) << 0;
99 }
100
101 @Override
102 public boolean hasAlpha() {
103 return false;
104 }
105
106 }