Source code: com/sixlegs/image/png/Chunk_PLTE.java
1 // Copyright (C) 1998, 1999, 2001 Chris Nokleberg
2 // Please see included LICENSE.TXT
3
4 package com.sixlegs.image.png;
5
6 import java.awt.image.IndexColorModel;
7 import java.io.IOException;
8
9 final class Chunk_PLTE
10 extends Chunk
11 {
12 private int size;
13
14 /* package */ int[] r_raw;
15 /* package */ int[] g_raw;
16 /* package */ int[] b_raw;
17 /* package */ int[] a_raw;
18
19 /* package */ byte[] r;
20 /* package */ byte[] g;
21 /* package */ byte[] b;
22 /* package */ byte[] a;
23
24 Chunk_PLTE()
25 {
26 super(PLTE);
27 }
28
29 protected boolean multipleOK()
30 {
31 return false;
32 }
33
34 protected boolean beforeIDAT()
35 {
36 return true;
37 }
38
39 protected void readData()
40 throws IOException
41 {
42 img.data.palette = this;
43 if (img.getChunk(bKGD) != null) {
44 throw new PngException("bKGD chunk must follow PLTE chunk");
45 }
46 if (!img.data.header.colorUsed) {
47 throw new PngExceptionSoft("PLTE chunk found in grayscale image");
48 }
49 if (length % 3 != 0) {
50 throw new PngException("PLTE chunk length indivisible by 3");
51 }
52 size = length / 3;
53
54 /// look into this
55 if (img.data.header.colorType == PngImage.COLOR_TYPE_PALETTE) {
56 if (size > (2 << img.data.header.depth)) {
57 throw new PngException("Too many palette entries");
58 } else if (size > 256) {
59 throw new PngExceptionSoft("Too many palette entries");
60 }
61 }
62
63 r = new byte[size];
64 g = new byte[size];
65 b = new byte[size];
66
67 int[][] raw = new int[3][size];
68 r_raw = raw[0];
69 g_raw = raw[1];
70 b_raw = raw[2];
71
72 for (int i = 0; i < size; i++) {
73 r_raw[i] = in_data.readUnsignedByte();
74 g_raw[i] = in_data.readUnsignedByte();
75 b_raw[i] = in_data.readUnsignedByte();
76 }
77
78 updateProperties(false);
79 }
80
81 // TODO: stop duplication of palette data?
82 /* package */ void updateProperties(boolean alpha)
83 {
84 int[][] prop = new int[alpha ? 4 : 3][size];
85 System.arraycopy(r_raw, 0, prop[0], 0, size);
86 System.arraycopy(g_raw, 0, prop[1], 0, size);
87 System.arraycopy(b_raw, 0, prop[2], 0, size);
88 if (alpha) {
89 System.arraycopy(a_raw, 0, prop[3], 0, size);
90 }
91 img.data.properties.put("palette", prop);
92 img.data.properties.put("palette size", new Integer(size));
93 }
94
95 /* package */ void calculate()
96 {
97 for (int i = 0; i < size; i++) {
98 r[i] = (byte)img.data.gammaTable[r_raw[i]];
99 g[i] = (byte)img.data.gammaTable[g_raw[i]];
100 b[i] = (byte)img.data.gammaTable[b_raw[i]];
101 }
102 if (img.data.header.paletteUsed) {
103 if (a != null) {
104 img.data.header.model =
105 new IndexColorModel(img.data.header.cmBits, size, r, g, b, a);
106 } else {
107 img.data.header.model =
108 new IndexColorModel(img.data.header.cmBits, size, r, g, b);
109 }
110 }
111 }
112 }