forked from apache/commons-imaging
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TiffImageWriterLossless.java
324 lines (281 loc) · 13.7 KB
/
TiffImageWriterLossless.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.formats.tiff.write;
import static org.apache.commons.imaging.formats.tiff.constants.TiffConstants.TIFF_HEADER_SIZE;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.imaging.FormatCompliance;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.ImageWriteException;
import org.apache.commons.imaging.common.BinaryOutputStream;
import org.apache.commons.imaging.common.bytesource.ByteSource;
import org.apache.commons.imaging.common.bytesource.ByteSourceArray;
import org.apache.commons.imaging.formats.tiff.JpegImageData;
import org.apache.commons.imaging.formats.tiff.TiffContents;
import org.apache.commons.imaging.formats.tiff.TiffDirectory;
import org.apache.commons.imaging.formats.tiff.TiffElement;
import org.apache.commons.imaging.formats.tiff.TiffElement.DataElement;
import org.apache.commons.imaging.formats.tiff.TiffField;
import org.apache.commons.imaging.formats.tiff.TiffImageData;
import org.apache.commons.imaging.formats.tiff.TiffImagingParameters;
import org.apache.commons.imaging.formats.tiff.TiffReader;
import org.apache.commons.imaging.formats.tiff.constants.ExifTagConstants;
public class TiffImageWriterLossless extends TiffImageWriterBase {
private final byte[] exifBytes;
private static final Comparator<TiffElement> ELEMENT_SIZE_COMPARATOR = Comparator.comparingInt(e -> e.length);
private static final Comparator<TiffOutputItem> ITEM_SIZE_COMPARATOR = Comparator.comparingInt(TiffOutputItem::getItemLength);
public TiffImageWriterLossless(final byte[] exifBytes) {
this.exifBytes = exifBytes;
}
public TiffImageWriterLossless(final ByteOrder byteOrder, final byte[] exifBytes) {
super(byteOrder);
this.exifBytes = exifBytes;
}
private List<TiffElement> analyzeOldTiff(final Map<Integer, TiffOutputField> frozenFields) throws ImageWriteException,
IOException {
try {
final ByteSource byteSource = new ByteSourceArray(exifBytes);
final FormatCompliance formatCompliance = FormatCompliance.getDefault();
final TiffContents contents = new TiffReader(false).readContents(
byteSource, new TiffImagingParameters(), formatCompliance);
final List<TiffElement> elements = new ArrayList<>();
final List<TiffDirectory> directories = contents.directories;
for (final TiffDirectory directory : directories) {
elements.add(directory);
for (final TiffField field : directory.getDirectoryEntries()) {
final TiffElement oversizeValue = field.getOversizeValueElement();
if (oversizeValue != null) {
final TiffOutputField frozenField = frozenFields.get(field.getTag());
if (frozenField != null
&& frozenField.getSeperateValue() != null
&& frozenField.bytesEqual(field.getByteArrayValue())) {
frozenField.getSeperateValue().setOffset(field.getOffset());
} else {
elements.add(oversizeValue);
}
}
}
final JpegImageData jpegImageData = directory.getJpegImageData();
if (jpegImageData != null) {
elements.add(jpegImageData);
}
final TiffImageData tiffImageData = directory.getTiffImageData();
if (tiffImageData != null) {
final DataElement[] data = tiffImageData.getImageData();
Collections.addAll(elements, data);
}
}
elements.sort(TiffElement.COMPARATOR);
final List<TiffElement> rewritableElements = new ArrayList<>();
final int TOLERANCE = 3;
TiffElement start = null;
long index = -1;
for (final TiffElement element : elements) {
final long lastElementByte = element.offset + element.length;
if (start == null) {
start = element;
index = lastElementByte;
} else if (element.offset - index > TOLERANCE) {
rewritableElements.add(new TiffElement.Stub(start.offset,
(int) (index - start.offset)));
start = element;
index = lastElementByte;
} else {
index = lastElementByte;
}
}
if (null != start) {
rewritableElements.add(new TiffElement.Stub(start.offset,
(int) (index - start.offset)));
}
return rewritableElements;
} catch (final ImageReadException e) {
throw new ImageWriteException(e.getMessage(), e);
}
}
@Override
public void write(final OutputStream os, final TiffOutputSet outputSet)
throws IOException, ImageWriteException {
// There are some fields whose address in the file must not change,
// unless of course their value is changed.
final Map<Integer, TiffOutputField> frozenFields = new HashMap<>();
final TiffOutputField makerNoteField = outputSet.findField(ExifTagConstants.EXIF_TAG_MAKER_NOTE);
if (makerNoteField != null && makerNoteField.getSeperateValue() != null) {
frozenFields.put(ExifTagConstants.EXIF_TAG_MAKER_NOTE.tag, makerNoteField);
}
final List<TiffElement> analysis = analyzeOldTiff(frozenFields);
final int oldLength = exifBytes.length;
if (analysis.isEmpty()) {
throw new ImageWriteException("Couldn't analyze old tiff data.");
}
if (analysis.size() == 1) {
final TiffElement onlyElement = analysis.get(0);
if (onlyElement.offset == TIFF_HEADER_SIZE
&& onlyElement.offset + onlyElement.length
+ TIFF_HEADER_SIZE == oldLength) {
// no gaps in old data, safe to complete overwrite.
new TiffImageWriterLossy(byteOrder).write(os, outputSet);
return;
}
}
final Map<Long, TiffOutputField> frozenFieldOffsets = new HashMap<>();
for (final Map.Entry<Integer, TiffOutputField> entry : frozenFields.entrySet()) {
final TiffOutputField frozenField = entry.getValue();
if (frozenField.getSeperateValue().getOffset() != TiffOutputItem.UNDEFINED_VALUE) {
frozenFieldOffsets.put(frozenField.getSeperateValue().getOffset(), frozenField);
}
}
final TiffOutputSummary outputSummary = validateDirectories(outputSet);
final List<TiffOutputItem> allOutputItems = outputSet.getOutputItems(outputSummary);
final List<TiffOutputItem> outputItems = new ArrayList<>();
for (final TiffOutputItem outputItem : allOutputItems) {
if (!frozenFieldOffsets.containsKey(outputItem.getOffset())) {
outputItems.add(outputItem);
}
}
final long outputLength = updateOffsetsStep(analysis, outputItems);
outputSummary.updateOffsets(byteOrder);
writeStep(os, outputSet, analysis, outputItems, outputLength);
}
private long updateOffsetsStep(final List<TiffElement> analysis,
final List<TiffOutputItem> outputItems) {
// items we cannot fit into a gap, we shall append to tail.
long overflowIndex = exifBytes.length;
// make copy.
final List<TiffElement> unusedElements = new ArrayList<>(analysis);
// should already be in order of offset, but make sure.
unusedElements.sort(TiffElement.COMPARATOR);
Collections.reverse(unusedElements);
// any items that represent a gap at the end of the exif segment, can be
// discarded.
while (!unusedElements.isEmpty()) {
final TiffElement element = unusedElements.get(0);
final long elementEnd = element.offset + element.length;
if (elementEnd != overflowIndex) {
break;
}
// discarding a tail element. should only happen once.
overflowIndex -= element.length;
unusedElements.remove(0);
}
unusedElements.sort(ELEMENT_SIZE_COMPARATOR);
Collections.reverse(unusedElements);
// make copy.
final List<TiffOutputItem> unplacedItems = new ArrayList<>(
outputItems);
unplacedItems.sort(ITEM_SIZE_COMPARATOR);
Collections.reverse(unplacedItems);
while (!unplacedItems.isEmpty()) {
// pop off largest unplaced item.
final TiffOutputItem outputItem = unplacedItems.remove(0);
final int outputItemLength = outputItem.getItemLength();
// search for the smallest possible element large enough to hold the
// item.
TiffElement bestFit = null;
for (final TiffElement element : unusedElements) {
if (element.length < outputItemLength) {
break;
}
bestFit = element;
}
if (null == bestFit) {
// we couldn't place this item. overflow.
if ((overflowIndex & 1L) != 0) {
overflowIndex += 1;
}
outputItem.setOffset(overflowIndex);
overflowIndex += outputItemLength;
} else {
long offset = bestFit.offset;
int length = bestFit.length;
if ((offset & 1L) != 0) {
offset += 1;
length -= 1;
}
outputItem.setOffset(offset);
unusedElements.remove(bestFit);
if (length > outputItemLength) {
// not a perfect fit.
final long excessOffset = offset + outputItemLength;
final int excessLength = length - outputItemLength;
unusedElements.add(new TiffElement.Stub(excessOffset,
excessLength));
// make sure the new element is in the correct order.
unusedElements.sort(ELEMENT_SIZE_COMPARATOR);
Collections.reverse(unusedElements);
}
}
}
return overflowIndex;
}
private static class BufferOutputStream extends OutputStream {
private final byte[] buffer;
private int index;
BufferOutputStream(final byte[] buffer, final int index) {
this.buffer = buffer;
this.index = index;
}
@Override
public void write(final int b) throws IOException {
if (index >= buffer.length) {
throw new IOException("Buffer overflow.");
}
buffer[index++] = (byte) b;
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
if (index + len > buffer.length) {
throw new IOException("Buffer overflow.");
}
System.arraycopy(b, off, buffer, index, len);
index += len;
}
}
private void writeStep(final OutputStream os, final TiffOutputSet outputSet,
final List<TiffElement> analysis, final List<TiffOutputItem> outputItems,
final long outputLength) throws IOException, ImageWriteException {
final TiffOutputDirectory rootDirectory = outputSet.getRootDirectory();
final byte[] output = new byte[(int) outputLength];
// copy old data (including maker notes, etc.)
System.arraycopy(exifBytes, 0, output, 0, Math.min(exifBytes.length, output.length));
final BufferOutputStream headerStream = new BufferOutputStream(output, 0);
final BinaryOutputStream headerBinaryStream = new BinaryOutputStream(headerStream, byteOrder);
writeImageFileHeader(headerBinaryStream, rootDirectory.getOffset());
// zero out the parsed pieces of old exif segment, in case we don't
// overwrite them.
for (final TiffElement element : analysis) {
Arrays.fill(output, (int) element.offset, (int) Math.min(element.offset + element.length, output.length),
(byte) 0);
}
// write in the new items
for (final TiffOutputItem outputItem : outputItems) {
try (BinaryOutputStream bos = new BinaryOutputStream(
new BufferOutputStream(output, (int) outputItem.getOffset()), byteOrder)) {
outputItem.writeItem(bos);
}
}
os.write(output);
}
}