1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.imaging.formats.png.chunks;
18
19 import static org.apache.commons.imaging.common.BinaryFunctions.readByte;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.IOException;
23 import java.util.Arrays;
24
25 import org.apache.commons.imaging.ImagingException;
26 import org.apache.commons.imaging.common.Allocator;
27 import org.apache.commons.imaging.formats.png.GammaCorrection;
28
29 public class PngChunkPlte extends PngChunk {
30 private final int[] rgb;
31
32 public PngChunkPlte(final int length, final int chunkType, final int crc, final byte[] bytes) throws ImagingException, IOException {
33 super(length, chunkType, crc, bytes);
34
35 final ByteArrayInputStream is = new ByteArrayInputStream(bytes);
36
37 if (length % 3 != 0) {
38 throw new ImagingException("PLTE: wrong length: " + length);
39 }
40
41 final int count = length / 3;
42
43 rgb = Allocator.intArray(count);
44
45 for (int i = 0; i < count; i++) {
46 final int red = readByte("red[" + i + "]", is, "Not a Valid PNG File: PLTE Corrupt");
47 final int green = readByte("green[" + i + "]", is, "Not a Valid PNG File: PLTE Corrupt");
48 final int blue = readByte("blue[" + i + "]", is, "Not a Valid PNG File: PLTE Corrupt");
49 rgb[i] = 0xff000000 | (0xff & red) << 16 | (0xff & green) << 8 | (0xff & blue) << 0;
50 }
51 }
52
53 public void correct(final GammaCorrection gammaCorrection) {
54 Arrays.setAll(rgb, i -> gammaCorrection.correctArgb(rgb[i]));
55 }
56
57 public int[] getRgb() {
58 return rgb.clone();
59 }
60
61
62
63
64
65
66
67
68
69
70
71
72 public int getRgb(final int index) throws ImagingException {
73 if (index < 0 || index >= rgb.length) {
74 throw new ImagingException("PNG: unknown Palette reference: " + index);
75 }
76 return rgb[index];
77 }
78
79 }