/
TiffWriter.java
429 lines (371 loc) · 14 KB
/
TiffWriter.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*
* #%L
* OME SCIFIO package for reading and converting scientific file formats.
* %%
* Copyright (C) 2005 - 2013 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package loci.formats.out;
import java.io.IOException;
import loci.common.RandomAccessInputStream;
import loci.common.RandomAccessOutputStream;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.FormatWriter;
import loci.formats.ImageTools;
import loci.formats.codec.CompressionType;
import loci.formats.gui.AWTImageTools;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffCompression;
import loci.formats.tiff.TiffParser;
import loci.formats.tiff.TiffRational;
import loci.formats.tiff.TiffSaver;
import ome.xml.model.primitives.PositiveFloat;
/**
* TiffWriter is the file format writer for TIFF files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/out/TiffWriter.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/out/TiffWriter.java;hb=HEAD">Gitweb</a></dd></dl>
*/
public class TiffWriter extends FormatWriter {
// -- Constants --
public static final String COMPRESSION_UNCOMPRESSED =
CompressionType.UNCOMPRESSED.getCompression();
public static final String COMPRESSION_LZW =
CompressionType.LZW.getCompression();
public static final String COMPRESSION_J2K =
CompressionType.J2K.getCompression();
public static final String COMPRESSION_J2K_LOSSY =
CompressionType.J2K_LOSSY.getCompression();
public static final String COMPRESSION_JPEG =
CompressionType.JPEG.getCompression();
// -- Fields --
/** Whether or not the output file is a BigTIFF file. */
protected boolean isBigTiff;
/** The TiffSaver that will do most of the writing. */
protected TiffSaver tiffSaver;
/** Input stream to use when overwriting data. */
protected RandomAccessInputStream in;
/** Whether or not to check the parameters passed to saveBytes. */
private boolean checkParams = true;
/**
* Sets the compression code for the specified IFD.
*
* @param ifd The IFD table to handle.
*/
private void formatCompression(IFD ifd)
throws FormatException
{
if (compression == null) compression = "";
TiffCompression compressType = TiffCompression.UNCOMPRESSED;
if (compression.equals(COMPRESSION_LZW)) {
compressType = TiffCompression.LZW;
}
else if (compression.equals(COMPRESSION_J2K)) {
compressType = TiffCompression.JPEG_2000;
}
else if (compression.equals(COMPRESSION_J2K_LOSSY)) {
compressType = TiffCompression.JPEG_2000_LOSSY;
}
else if (compression.equals(COMPRESSION_JPEG)) {
compressType = TiffCompression.JPEG;
}
Object v = ifd.get(new Integer(IFD.COMPRESSION));
if (v == null)
ifd.put(new Integer(IFD.COMPRESSION), compressType.getCode());
}
// -- Constructors --
public TiffWriter() {
this("Tagged Image File Format", new String[] {"tif", "tiff"});
}
public TiffWriter(String format, String[] exts) {
super(format, exts);
compressionTypes = new String[] {
COMPRESSION_UNCOMPRESSED,
COMPRESSION_LZW,
COMPRESSION_J2K,
COMPRESSION_J2K_LOSSY,
COMPRESSION_JPEG
};
isBigTiff = false;
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#setId(String) */
public void setId(String id) throws FormatException, IOException {
super.setId(id);
synchronized (this) {
setupTiffSaver();
}
}
// -- TiffWriter API methods --
/**
* Saves the given image to the specified (possibly already open) file.
* The IFD hashtable allows specification of TIFF parameters such as bit
* depth, compression and units.
*/
public void saveBytes(int no, byte[] buf, IFD ifd)
throws IOException, FormatException
{
MetadataRetrieve r = getMetadataRetrieve();
int w = r.getPixelsSizeX(series).getValue().intValue();
int h = r.getPixelsSizeY(series).getValue().intValue();
saveBytes(no, buf, ifd, 0, 0, w, h);
}
/**
* Saves the given image to the specified series in the current file.
* The IFD hashtable allows specification of TIFF parameters such as bit
* depth, compression and units.
*/
public void saveBytes(int no, byte[] buf, IFD ifd, int x, int y, int w, int h)
throws IOException, FormatException
{
if (checkParams) checkParams(no, buf, x, y, w, h);
if (ifd == null) ifd = new IFD();
MetadataRetrieve retrieve = getMetadataRetrieve();
int type = FormatTools.pixelTypeFromString(
retrieve.getPixelsType(series).toString());
int index = no;
// This operation is synchronized
synchronized (this) {
// This operation is synchronized against the TIFF saver.
synchronized (tiffSaver) {
index = prepareToWriteImage(no, buf, ifd, x, y, w, h);
if (index == -1) {
return;
}
}
}
tiffSaver.writeImage(buf, ifd, index, type, x, y, w, h,
no == getPlaneCount() - 1 && getSeries() == retrieve.getImageCount() - 1);
}
/**
* Performs the preparation for work prior to the usage of the TIFF saver.
* This method is factored out from <code>saveBytes()</code> in an attempt to
* ensure thread safety.
*/
private int prepareToWriteImage(
int no, byte[] buf, IFD ifd, int x, int y, int w, int h)
throws IOException, FormatException {
MetadataRetrieve retrieve = getMetadataRetrieve();
Boolean bigEndian = retrieve.getPixelsBinDataBigEndian(series, 0);
boolean littleEndian = bigEndian == null ?
false : !bigEndian.booleanValue();
// Ensure that no more than one thread manipulated the initialized array
// at one time.
synchronized (this) {
if (no < initialized[series].length && !initialized[series][no]) {
initialized[series][no] = true;
RandomAccessInputStream tmp = new RandomAccessInputStream(currentId);
if (tmp.length() == 0) {
synchronized (this) {
// write TIFF header
tiffSaver.writeHeader();
}
}
tmp.close();
}
}
int c = getSamplesPerPixel();
int type = FormatTools.pixelTypeFromString(
retrieve.getPixelsType(series).toString());
int bytesPerPixel = FormatTools.getBytesPerPixel(type);
int blockSize = w * h * c * bytesPerPixel;
if (blockSize > buf.length) {
c = buf.length / (w * h * bytesPerPixel);
}
if (bytesPerPixel > 1 && c != 1 && c != 3) {
// split channels
checkParams = false;
if (no == 0) {
initialized[series] = new boolean[initialized[series].length * c];
}
for (int i=0; i<c; i++) {
byte[] b = ImageTools.splitChannels(buf, i, c, bytesPerPixel,
false, interleaved);
saveBytes(no * c + i, b, (IFD) ifd.clone(), x, y, w, h);
}
checkParams = true;
return -1;
}
formatCompression(ifd);
byte[][] lut = AWTImageTools.get8BitLookupTable(cm);
if (lut != null) {
int[] colorMap = new int[lut.length * lut[0].length];
for (int i=0; i<lut.length; i++) {
for (int j=0; j<lut[0].length; j++) {
colorMap[i * lut[0].length + j] = (int) ((lut[i][j] & 0xff) << 8);
}
}
ifd.putIFDValue(IFD.COLOR_MAP, colorMap);
}
int width = retrieve.getPixelsSizeX(series).getValue().intValue();
int height = retrieve.getPixelsSizeY(series).getValue().intValue();
ifd.put(new Integer(IFD.IMAGE_WIDTH), new Long(width));
ifd.put(new Integer(IFD.IMAGE_LENGTH), new Long(height));
PositiveFloat px = retrieve.getPixelsPhysicalSizeX(series);
Double physicalSizeX = px == null ? null : px.getValue();
if (physicalSizeX == null || physicalSizeX.doubleValue() == 0) {
physicalSizeX = 0d;
}
else physicalSizeX = 1d / physicalSizeX;
PositiveFloat py = retrieve.getPixelsPhysicalSizeY(series);
Double physicalSizeY = py == null ? null : py.getValue();
if (physicalSizeY == null || physicalSizeY.doubleValue() == 0) {
physicalSizeY = 0d;
}
else physicalSizeY = 1d / physicalSizeY;
ifd.put(IFD.RESOLUTION_UNIT, 3);
ifd.put(IFD.X_RESOLUTION,
new TiffRational((long) (physicalSizeX * 1000 * 10000), 1000));
ifd.put(IFD.Y_RESOLUTION,
new TiffRational((long) (physicalSizeY * 1000 * 10000), 1000));
if (!isBigTiff) {
isBigTiff = (out.length() + 2
* (width * height * c * bytesPerPixel)) >= 4294967296L;
if (isBigTiff) {
throw new FormatException("File is too large; call setBigTiff(true)");
}
}
// write the image
ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(littleEndian));
if (!ifd.containsKey(IFD.REUSE)) {
ifd.put(IFD.REUSE, out.length());
out.seek(out.length());
}
else {
out.seek((Long) ifd.get(IFD.REUSE));
}
ifd.putIFDValue(IFD.PLANAR_CONFIGURATION,
interleaved || getSamplesPerPixel() == 1 ? 1 : 2);
int sampleFormat = 1;
if (FormatTools.isSigned(type)) sampleFormat = 2;
if (FormatTools.isFloatingPoint(type)) sampleFormat = 3;
ifd.putIFDValue(IFD.SAMPLE_FORMAT, sampleFormat);
int index = no;
int realSeries = getSeries();
for (int i=0; i<realSeries; i++) {
setSeries(i);
index += getPlaneCount();
}
setSeries(realSeries);
return index;
}
// -- FormatWriter API methods --
/* (non-Javadoc)
* @see loci.formats.FormatWriter#close()
*/
@Override
public void close() throws IOException {
super.close();
if (in != null) {
in.close();
}
}
/* @see loci.formats.FormatWriter#getPlaneCount() */
public int getPlaneCount() {
MetadataRetrieve retrieve = getMetadataRetrieve();
int c = getSamplesPerPixel();
int type = FormatTools.pixelTypeFromString(
retrieve.getPixelsType(series).toString());
int bytesPerPixel = FormatTools.getBytesPerPixel(type);
if (bytesPerPixel > 1 && c != 1 && c != 3) {
return super.getPlaneCount() * c;
}
return super.getPlaneCount();
}
// -- IFormatWriter API methods --
/**
* @see loci.formats.IFormatWriter#saveBytes(int, byte[], int, int, int, int)
*/
public void saveBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
IFD ifd = new IFD();
if (!sequential) {
TiffParser parser = new TiffParser(currentId);
try {
long[] ifdOffsets = parser.getIFDOffsets();
if (no < ifdOffsets.length) {
ifd = parser.getIFD(ifdOffsets[no]);
}
}
finally {
RandomAccessInputStream tiffParserStream = parser.getStream();
if (tiffParserStream != null) {
tiffParserStream.close();
}
}
}
saveBytes(no, buf, ifd, x, y, w, h);
}
/* @see loci.formats.IFormatWriter#canDoStacks(String) */
public boolean canDoStacks() { return true; }
/* @see loci.formats.IFormatWriter#getPixelTypes(String) */
public int[] getPixelTypes(String codec) {
if (codec != null && codec.equals(COMPRESSION_JPEG)) {
return new int[] {FormatTools.INT8, FormatTools.UINT8,
FormatTools.INT16, FormatTools.UINT16};
}
else if (codec != null && codec.equals(COMPRESSION_J2K)) {
return new int[] {FormatTools.INT8, FormatTools.UINT8,
FormatTools.INT16, FormatTools.UINT16, FormatTools.INT32,
FormatTools.UINT32, FormatTools.FLOAT};
}
return new int[] {FormatTools.INT8, FormatTools.UINT8, FormatTools.INT16,
FormatTools.UINT16, FormatTools.INT32, FormatTools.UINT32,
FormatTools.FLOAT, FormatTools.DOUBLE};
}
// -- TiffWriter API methods --
/**
* Sets whether or not BigTIFF files should be written.
* This flag is not reset when close() is called.
*/
public void setBigTiff(boolean bigTiff) {
FormatTools.assertId(currentId, false, 1);
isBigTiff = bigTiff;
}
// -- Helper methods --
private void setupTiffSaver() throws IOException {
out.close();
out = new RandomAccessOutputStream(currentId);
tiffSaver = new TiffSaver(out, currentId);
MetadataRetrieve retrieve = getMetadataRetrieve();
Boolean bigEndian = retrieve.getPixelsBinDataBigEndian(series, 0);
boolean littleEndian = bigEndian == null ?
false : !bigEndian.booleanValue();
tiffSaver.setWritingSequentially(sequential);
tiffSaver.setLittleEndian(littleEndian);
tiffSaver.setBigTiff(isBigTiff);
tiffSaver.setCodecOptions(options);
}
}