-
Notifications
You must be signed in to change notification settings - Fork 242
/
JPEGReader.java
276 lines (238 loc) · 8.8 KB
/
JPEGReader.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
/*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2017 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.
* #L%
*/
package loci.formats.in;
import java.awt.color.CMMException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import loci.common.ByteArrayHandle;
import loci.common.DataTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.DelegateReader;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.services.EXIFService;
import java.util.Date;
import java.util.HashMap;
import org.joda.time.DateTime;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.Timestamp;
/**
* JPEGReader is the file format reader for JPEG images.
*
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class JPEGReader extends DelegateReader {
// -- Constants --
private static final int MAX_SIZE = 8192;
/**
* setId may alter the "useLegacy" variable depending upon
* the type of JPEG encountered. Storing the state of
* the "useLegacy" variable prior to any internal changes
* allows the reader to reset "useLegacy" to its original
* state upon close.
*/
private boolean initialUseLegacy;
// -- Constructor --
/** Constructs a new JPEGReader. */
public JPEGReader() {
super("JPEG", new String[] {"jpg", "jpeg", "jpe"});
nativeReader = new DefaultJPEGReader();
legacyReader = new TileJPEGReader();
nativeReaderInitialized = false;
legacyReaderInitialized = false;
domains = new String[] {FormatTools.GRAPHICS_DOMAIN};
suffixNecessary = false;
}
// -- FormatReader API methods --
/* @see FormatReader#setId(String) */
@Override
public void setId(String id) throws FormatException, IOException {
// capture the current state of "useLegacy"
// it may be updated later in this method and should be reset upon close
initialUseLegacy = isLegacy();
try {
super.setId(id);
}
catch (CMMException e) {
// strip out all but the first application marker
// ImageIO isn't too keen on supporting multiple application markers
// in the same stream, as evidenced by:
//
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488904
in = new RandomAccessInputStream(id);
ByteArrayOutputStream v = new ByteArrayOutputStream();
byte[] tag = new byte[2];
in.read(tag);
v.write(tag);
in.read(tag);
int tagValue = DataTools.bytesToShort(tag, false) & 0xffff;
boolean appNoteFound = false;
while (tagValue != 0xffdb) {
if (!appNoteFound || (tagValue < 0xffe0 && tagValue >= 0xfff0)) {
v.write(tag);
in.read(tag);
int len = DataTools.bytesToShort(tag, false) & 0xffff;
byte[] tagContents = new byte[len - 2];
in.read(tagContents);
v.write(tag);
v.write(tagContents);
}
else {
in.read(tag);
int len = DataTools.bytesToShort(tag, false) & 0xffff;
in.skipBytes(len - 2);
}
if (tagValue >= 0xffe0 && tagValue < 0xfff0 && !appNoteFound) {
appNoteFound = true;
}
in.read(tag);
tagValue = DataTools.bytesToShort(tag, false) & 0xffff;
}
v.write(tag);
byte[] remainder = new byte[(int) (in.length() - in.getFilePointer())];
in.read(remainder);
v.write(remainder);
ByteArrayHandle bytes = new ByteArrayHandle(v.toByteArray());
Location.mapFile(currentId + ".fixed", bytes);
super.setId(currentId + ".fixed");
}
if (getSizeX() > MAX_SIZE && getSizeY() > MAX_SIZE &&
!legacyReaderInitialized)
{
// this is a large image, so try to open with TileJPEGReader first
// TileJPEGReader requires restart markers to be present; if this file
// doesn't contain restarts then TileJPEGReader will throw IOException
// and we'll try again with DefaultJPEGReader
close();
useLegacy = true;
try {
super.setId(id);
}
catch (IOException e) {
// this case usually requires a lot of memory as it's a big image
// that requires the whole image to be opened for any size tile
LOGGER.debug("Initialization with TileJPEGReader failed", e);
close();
useLegacy = false;
super.setId(id);
}
}
if (currentId.endsWith(".fixed")) {
currentId = currentId.substring(0, currentId.lastIndexOf("."));
}
}
// -- IFormatReader API methods --
/* @see IFormatReader#getSeriesUsedFiles(boolean) */
@Override
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
return noPixels ? null : new String[] {currentId.replaceAll(".fixed", "")};
}
/* @see IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
Location.mapId(currentId, null);
// reset to whatever legacy setting was originally requested
// this erases any changes made during setId
setLegacy(initialUseLegacy);
}
// -- Helper reader --
public static class DefaultJPEGReader extends ImageIOReader {
public DefaultJPEGReader() {
super("JPEG", new String[] {"jpg", "jpeg", "jpe"});
suffixNecessary = false;
suffixSufficient = false;
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
if (open) {
return super.isThisType(name, open);
}
return checkSuffix(name, getSuffixes());
}
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
try {
super.initFile(id);
}
catch (IllegalArgumentException e) {
throw new FormatException(e);
}
MetadataStore store = makeFilterMetadata();
LOGGER.info("Parsing JPEG EXIF data");
try {
EXIFService exif = new ServiceFactory().getInstance(EXIFService.class);
if (exif == null) {
return;
}
exif.initialize(id);
// Set the acquisition date
Date date = exif.getCreationDate();
if (date != null) {
Timestamp timestamp = new Timestamp(new DateTime(date));
store.setImageAcquisitionDate(timestamp, 0);
}
HashMap<String, String> tags = exif.getTags();
for (String tagName : tags.keySet()) {
addGlobalMeta(tagName, tags.get(tagName));
}
}
catch (ServiceException e) {
LOGGER.debug("Could not parse EXIF data", e);
}
catch (DependencyException e) {
LOGGER.debug("Could not parse EXIF data", e);
}
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException
{
final int blockLen = 4;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
byte[] signature = new byte[blockLen];
stream.read(signature);
if (signature[0] != (byte) 0xff || signature[1] != (byte) 0xd8 ||
signature[2] != (byte) 0xff || ((int) signature[3] & 0xf0) == 0)
{
return false;
}
return true;
}
}
}