1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.imaging.formats.webp.chunks;
18
19 import java.io.IOException;
20 import java.io.PrintWriter;
21 import java.nio.ByteOrder;
22 import java.nio.charset.StandardCharsets;
23
24 import org.apache.commons.imaging.ImagingException;
25 import org.apache.commons.imaging.common.BinaryFileParser;
26 import org.apache.commons.imaging.internal.SafeOperations;
27
28
29
30
31
32
33
34 public abstract class WebPChunk extends BinaryFileParser {
35 private final int type;
36 private final int size;
37 protected final byte[] bytes;
38 private final int chunkSize;
39
40
41
42
43
44
45
46
47
48 WebPChunk(final int type, final int size, final byte[] bytes) throws ImagingException {
49 super(ByteOrder.LITTLE_ENDIAN);
50
51 if (size != bytes.length) {
52 throw new ImagingException("Chunk size must match bytes length");
53 }
54
55 this.type = type;
56 this.size = size;
57 this.bytes = bytes;
58
59
60 final int padding = size % 2 != 0 ? 1 : 0;
61
62
63 this.chunkSize = SafeOperations.add(4, 4, size, padding);
64 }
65
66
67
68
69
70
71
72
73
74 public void dump(final PrintWriter pw, final int offset) throws ImagingException, IOException {
75 pw.printf("Chunk %s at offset %s, length %d%n, payload size %d%n", getTypeDescription(), offset >= 0 ? String.valueOf(offset) : "unknown",
76 getChunkSize(), getPayloadSize());
77 }
78
79
80
81
82 public byte[] getBytes() {
83 return bytes.clone();
84 }
85
86
87
88
89 public int getChunkSize() {
90 return chunkSize;
91 }
92
93
94
95
96 public int getPayloadSize() {
97 return size;
98 }
99
100
101
102
103 public int getType() {
104 return type;
105 }
106
107
108
109
110 public String getTypeDescription() {
111 return new String(new byte[] { (byte) (type & 0xff), (byte) (type >> 8 & 0xff), (byte) (type >> 16 & 0xff), (byte) (type >> 24 & 0xff) },
112 StandardCharsets.UTF_8);
113 }
114 }