1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.awt.Color;
|
---|
7 | import java.awt.Cursor;
|
---|
8 | import java.awt.Dimension;
|
---|
9 | import java.awt.Graphics2D;
|
---|
10 | import java.awt.GraphicsEnvironment;
|
---|
11 | import java.awt.Image;
|
---|
12 | import java.awt.Point;
|
---|
13 | import java.awt.Rectangle;
|
---|
14 | import java.awt.RenderingHints;
|
---|
15 | import java.awt.Toolkit;
|
---|
16 | import java.awt.Transparency;
|
---|
17 | import java.awt.image.BufferedImage;
|
---|
18 | import java.awt.image.ColorModel;
|
---|
19 | import java.awt.image.FilteredImageSource;
|
---|
20 | import java.awt.image.ImageFilter;
|
---|
21 | import java.awt.image.ImageProducer;
|
---|
22 | import java.awt.image.RGBImageFilter;
|
---|
23 | import java.awt.image.RenderedImage;
|
---|
24 | import java.awt.image.WritableRaster;
|
---|
25 | import java.io.ByteArrayInputStream;
|
---|
26 | import java.io.ByteArrayOutputStream;
|
---|
27 | import java.io.File;
|
---|
28 | import java.io.IOException;
|
---|
29 | import java.io.InputStream;
|
---|
30 | import java.io.StringReader;
|
---|
31 | import java.net.URI;
|
---|
32 | import java.net.URL;
|
---|
33 | import java.nio.charset.StandardCharsets;
|
---|
34 | import java.nio.file.InvalidPathException;
|
---|
35 | import java.util.Arrays;
|
---|
36 | import java.util.Base64;
|
---|
37 | import java.util.Collection;
|
---|
38 | import java.util.EnumMap;
|
---|
39 | import java.util.Hashtable;
|
---|
40 | import java.util.Iterator;
|
---|
41 | import java.util.LinkedList;
|
---|
42 | import java.util.List;
|
---|
43 | import java.util.Map;
|
---|
44 | import java.util.Objects;
|
---|
45 | import java.util.concurrent.CompletableFuture;
|
---|
46 | import java.util.concurrent.ConcurrentHashMap;
|
---|
47 | import java.util.concurrent.ExecutorService;
|
---|
48 | import java.util.concurrent.Executors;
|
---|
49 | import java.util.function.Consumer;
|
---|
50 | import java.util.function.Function;
|
---|
51 | import java.util.function.UnaryOperator;
|
---|
52 | import java.util.regex.Matcher;
|
---|
53 | import java.util.regex.Pattern;
|
---|
54 | import java.util.stream.IntStream;
|
---|
55 | import java.util.zip.ZipEntry;
|
---|
56 | import java.util.zip.ZipFile;
|
---|
57 |
|
---|
58 | import javax.imageio.IIOException;
|
---|
59 | import javax.imageio.ImageIO;
|
---|
60 | import javax.imageio.ImageReadParam;
|
---|
61 | import javax.imageio.ImageReader;
|
---|
62 | import javax.imageio.metadata.IIOMetadata;
|
---|
63 | import javax.imageio.stream.ImageInputStream;
|
---|
64 | import javax.swing.ImageIcon;
|
---|
65 | import javax.xml.parsers.ParserConfigurationException;
|
---|
66 |
|
---|
67 | import org.openstreetmap.josm.data.Preferences;
|
---|
68 | import org.openstreetmap.josm.data.osm.OsmPrimitive;
|
---|
69 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
70 | import org.openstreetmap.josm.io.CachedFile;
|
---|
71 | import org.openstreetmap.josm.spi.preferences.Config;
|
---|
72 | import org.w3c.dom.Element;
|
---|
73 | import org.w3c.dom.Node;
|
---|
74 | import org.w3c.dom.NodeList;
|
---|
75 | import org.xml.sax.Attributes;
|
---|
76 | import org.xml.sax.InputSource;
|
---|
77 | import org.xml.sax.SAXException;
|
---|
78 | import org.xml.sax.XMLReader;
|
---|
79 | import org.xml.sax.helpers.DefaultHandler;
|
---|
80 |
|
---|
81 | import com.kitfox.svg.SVGDiagram;
|
---|
82 | import com.kitfox.svg.SVGException;
|
---|
83 | import com.kitfox.svg.SVGUniverse;
|
---|
84 |
|
---|
85 | /**
|
---|
86 | * Helper class to support the application with images.
|
---|
87 | * <p>
|
---|
88 | * How to use:
|
---|
89 | * <p>
|
---|
90 | * <code>ImageIcon icon = new ImageProvider(name).setMaxSize(ImageSizes.MAP).get();</code>
|
---|
91 | * (there are more options, see below)
|
---|
92 | * <p>
|
---|
93 | * short form:
|
---|
94 | * <code>ImageIcon icon = ImageProvider.get(name);</code>
|
---|
95 | *
|
---|
96 | * @author imi
|
---|
97 | */
|
---|
98 | public class ImageProvider {
|
---|
99 |
|
---|
100 | // CHECKSTYLE.OFF: SingleSpaceSeparator
|
---|
101 | private static final String HTTP_PROTOCOL = "http://";
|
---|
102 | private static final String HTTPS_PROTOCOL = "https://";
|
---|
103 | private static final String WIKI_PROTOCOL = "wiki://";
|
---|
104 | // CHECKSTYLE.ON: SingleSpaceSeparator
|
---|
105 |
|
---|
106 | /**
|
---|
107 | * Supported image types
|
---|
108 | */
|
---|
109 | public enum ImageType {
|
---|
110 | /** Scalable vector graphics */
|
---|
111 | SVG,
|
---|
112 | /** Everything else, e.g. png, gif (must be supported by Java) */
|
---|
113 | OTHER
|
---|
114 | }
|
---|
115 |
|
---|
116 | /**
|
---|
117 | * Supported image sizes
|
---|
118 | * @since 7687
|
---|
119 | */
|
---|
120 | public enum ImageSizes {
|
---|
121 | /** SMALL_ICON value of an Action */
|
---|
122 | SMALLICON(Config.getPref().getInt("iconsize.smallicon", 16)),
|
---|
123 | /** LARGE_ICON_KEY value of an Action */
|
---|
124 | LARGEICON(Config.getPref().getInt("iconsize.largeicon", 24)),
|
---|
125 | /** map icon */
|
---|
126 | MAP(Config.getPref().getInt("iconsize.map", 16)),
|
---|
127 | /** map icon maximum size */
|
---|
128 | MAPMAX(Config.getPref().getInt("iconsize.mapmax", 48)),
|
---|
129 | /** cursor icon size */
|
---|
130 | CURSOR(Config.getPref().getInt("iconsize.cursor", 32)),
|
---|
131 | /** cursor overlay icon size */
|
---|
132 | CURSOROVERLAY(CURSOR),
|
---|
133 | /** menu icon size */
|
---|
134 | MENU(SMALLICON),
|
---|
135 | /** menu icon size in popup menus
|
---|
136 | * @since 8323
|
---|
137 | */
|
---|
138 | POPUPMENU(LARGEICON),
|
---|
139 | /** Layer list icon size
|
---|
140 | * @since 8323
|
---|
141 | */
|
---|
142 | LAYER(Config.getPref().getInt("iconsize.layer", 16)),
|
---|
143 | /** Table icon size
|
---|
144 | * @since 15049
|
---|
145 | */
|
---|
146 | TABLE(SMALLICON),
|
---|
147 | /** Toolbar button icon size
|
---|
148 | * @since 9253
|
---|
149 | */
|
---|
150 | TOOLBAR(LARGEICON),
|
---|
151 | /** Side button maximum height
|
---|
152 | * @since 9253
|
---|
153 | */
|
---|
154 | SIDEBUTTON(Config.getPref().getInt("iconsize.sidebutton", 20)),
|
---|
155 | /** Settings tab icon size
|
---|
156 | * @since 9253
|
---|
157 | */
|
---|
158 | SETTINGS_TAB(Config.getPref().getInt("iconsize.settingstab", 48)),
|
---|
159 | /**
|
---|
160 | * The default image size
|
---|
161 | * @since 9705
|
---|
162 | */
|
---|
163 | DEFAULT(Config.getPref().getInt("iconsize.default", 24)),
|
---|
164 | /**
|
---|
165 | * Splash dialog logo size
|
---|
166 | * @since 10358
|
---|
167 | */
|
---|
168 | SPLASH_LOGO(128, 128),
|
---|
169 | /**
|
---|
170 | * About dialog logo size
|
---|
171 | * @since 10358
|
---|
172 | */
|
---|
173 | ABOUT_LOGO(256, 256),
|
---|
174 | /**
|
---|
175 | * Status line logo size
|
---|
176 | * @since 13369
|
---|
177 | */
|
---|
178 | STATUSLINE(18, 18),
|
---|
179 | /**
|
---|
180 | * HTML inline image
|
---|
181 | * @since 16872
|
---|
182 | */
|
---|
183 | HTMLINLINE(24, 24);
|
---|
184 |
|
---|
185 | private final int virtualWidth;
|
---|
186 | private final int virtualHeight;
|
---|
187 |
|
---|
188 | ImageSizes(int imageSize) {
|
---|
189 | this.virtualWidth = imageSize;
|
---|
190 | this.virtualHeight = imageSize;
|
---|
191 | }
|
---|
192 |
|
---|
193 | ImageSizes(int width, int height) {
|
---|
194 | this.virtualWidth = width;
|
---|
195 | this.virtualHeight = height;
|
---|
196 | }
|
---|
197 |
|
---|
198 | ImageSizes(ImageSizes that) {
|
---|
199 | this.virtualWidth = that.virtualWidth;
|
---|
200 | this.virtualHeight = that.virtualHeight;
|
---|
201 | }
|
---|
202 |
|
---|
203 | /**
|
---|
204 | * Returns the image width in virtual pixels
|
---|
205 | * @return the image width in virtual pixels
|
---|
206 | * @since 9705
|
---|
207 | */
|
---|
208 | public int getVirtualWidth() {
|
---|
209 | return virtualWidth;
|
---|
210 | }
|
---|
211 |
|
---|
212 | /**
|
---|
213 | * Returns the image height in virtual pixels
|
---|
214 | * @return the image height in virtual pixels
|
---|
215 | * @since 9705
|
---|
216 | */
|
---|
217 | public int getVirtualHeight() {
|
---|
218 | return virtualHeight;
|
---|
219 | }
|
---|
220 |
|
---|
221 | /**
|
---|
222 | * Returns the image width in pixels to use for display
|
---|
223 | * @return the image width in pixels to use for display
|
---|
224 | * @since 10484
|
---|
225 | */
|
---|
226 | public int getAdjustedWidth() {
|
---|
227 | return GuiSizesHelper.getSizeDpiAdjusted(virtualWidth);
|
---|
228 | }
|
---|
229 |
|
---|
230 | /**
|
---|
231 | * Returns the image height in pixels to use for display
|
---|
232 | * @return the image height in pixels to use for display
|
---|
233 | * @since 10484
|
---|
234 | */
|
---|
235 | public int getAdjustedHeight() {
|
---|
236 | return GuiSizesHelper.getSizeDpiAdjusted(virtualHeight);
|
---|
237 | }
|
---|
238 |
|
---|
239 | /**
|
---|
240 | * Returns the image size as dimension
|
---|
241 | * @return the image size as dimension
|
---|
242 | * @since 9705
|
---|
243 | */
|
---|
244 | public Dimension getImageDimension() {
|
---|
245 | return new Dimension(virtualWidth, virtualHeight);
|
---|
246 | }
|
---|
247 | }
|
---|
248 |
|
---|
249 | private enum ImageLocations {
|
---|
250 | LOCAL,
|
---|
251 | ARCHIVE
|
---|
252 | }
|
---|
253 |
|
---|
254 | /**
|
---|
255 | * Property set on {@code BufferedImage} returned by {@link #makeImageTransparent}.
|
---|
256 | * @since 7132
|
---|
257 | */
|
---|
258 | public static final String PROP_TRANSPARENCY_FORCED = "josm.transparency.forced";
|
---|
259 |
|
---|
260 | /**
|
---|
261 | * Property set on {@code BufferedImage} returned by {@link #read} if metadata is required.
|
---|
262 | * @since 7132
|
---|
263 | */
|
---|
264 | public static final String PROP_TRANSPARENCY_COLOR = "josm.transparency.color";
|
---|
265 |
|
---|
266 | /** directories in which images are searched */
|
---|
267 | protected Collection<String> dirs;
|
---|
268 | /** caching identifier */
|
---|
269 | protected String id;
|
---|
270 | /** sub directory the image can be found in */
|
---|
271 | protected String subdir;
|
---|
272 | /** image file name */
|
---|
273 | protected final String name;
|
---|
274 | /** archive file to take image from */
|
---|
275 | protected File archive;
|
---|
276 | /** directory inside the archive */
|
---|
277 | protected String inArchiveDir;
|
---|
278 | /** virtual width of the resulting image, -1 when original image data should be used */
|
---|
279 | protected int virtualWidth = -1;
|
---|
280 | /** virtual height of the resulting image, -1 when original image data should be used */
|
---|
281 | protected int virtualHeight = -1;
|
---|
282 | /** virtual maximum width of the resulting image, -1 for no restriction */
|
---|
283 | protected int virtualMaxWidth = -1;
|
---|
284 | /** virtual maximum height of the resulting image, -1 for no restriction */
|
---|
285 | protected int virtualMaxHeight = -1;
|
---|
286 | /** In case of errors do not throw exception but return <code>null</code> for missing image */
|
---|
287 | protected boolean optional;
|
---|
288 | /** <code>true</code> if warnings should be suppressed */
|
---|
289 | protected boolean suppressWarnings;
|
---|
290 | /** ordered list of overlay images */
|
---|
291 | protected List<ImageOverlay> overlayInfo;
|
---|
292 | /** <code>true</code> if icon must be grayed out */
|
---|
293 | protected boolean isDisabled;
|
---|
294 | /** <code>true</code> if multi-resolution image is requested */
|
---|
295 | protected boolean multiResolution = true;
|
---|
296 |
|
---|
297 | private static SVGUniverse svgUniverse;
|
---|
298 |
|
---|
299 | /**
|
---|
300 | * The icon cache
|
---|
301 | */
|
---|
302 | private static final Map<String, ImageResource> cache = new ConcurrentHashMap<>();
|
---|
303 |
|
---|
304 | /** small cache of critical images used in many parts of the application */
|
---|
305 | private static final Map<OsmPrimitiveType, ImageIcon> osmPrimitiveTypeCache = new EnumMap<>(OsmPrimitiveType.class);
|
---|
306 |
|
---|
307 | private static final ExecutorService IMAGE_FETCHER =
|
---|
308 | Executors.newSingleThreadExecutor(Utils.newThreadFactory("image-fetcher-%d", Thread.NORM_PRIORITY));
|
---|
309 |
|
---|
310 | /**
|
---|
311 | * Constructs a new {@code ImageProvider} from a filename in a given directory.
|
---|
312 | * @param subdir subdirectory the image lies in
|
---|
313 | * @param name the name of the image. If it does not end with '.png' or '.svg',
|
---|
314 | * both extensions are tried.
|
---|
315 | * @throws NullPointerException if name is null
|
---|
316 | */
|
---|
317 | public ImageProvider(String subdir, String name) {
|
---|
318 | this.subdir = subdir;
|
---|
319 | this.name = Objects.requireNonNull(name, "name");
|
---|
320 | }
|
---|
321 |
|
---|
322 | /**
|
---|
323 | * Constructs a new {@code ImageProvider} from a filename.
|
---|
324 | * @param name the name of the image. If it does not end with '.png' or '.svg',
|
---|
325 | * both extensions are tried.
|
---|
326 | * @throws NullPointerException if name is null
|
---|
327 | */
|
---|
328 | public ImageProvider(String name) {
|
---|
329 | this.name = Objects.requireNonNull(name, "name");
|
---|
330 | }
|
---|
331 |
|
---|
332 | /**
|
---|
333 | * Constructs a new {@code ImageProvider} from an existing one.
|
---|
334 | * @param image the existing image provider to be copied
|
---|
335 | * @since 8095
|
---|
336 | */
|
---|
337 | public ImageProvider(ImageProvider image) {
|
---|
338 | this.dirs = image.dirs;
|
---|
339 | this.id = image.id;
|
---|
340 | this.subdir = image.subdir;
|
---|
341 | this.name = image.name;
|
---|
342 | this.archive = image.archive;
|
---|
343 | this.inArchiveDir = image.inArchiveDir;
|
---|
344 | this.virtualWidth = image.virtualWidth;
|
---|
345 | this.virtualHeight = image.virtualHeight;
|
---|
346 | this.virtualMaxWidth = image.virtualMaxWidth;
|
---|
347 | this.virtualMaxHeight = image.virtualMaxHeight;
|
---|
348 | this.optional = image.optional;
|
---|
349 | this.suppressWarnings = image.suppressWarnings;
|
---|
350 | this.overlayInfo = image.overlayInfo;
|
---|
351 | this.isDisabled = image.isDisabled;
|
---|
352 | this.multiResolution = image.multiResolution;
|
---|
353 | }
|
---|
354 |
|
---|
355 | /**
|
---|
356 | * Directories to look for the image.
|
---|
357 | * @param dirs The directories to look for.
|
---|
358 | * @return the current object, for convenience
|
---|
359 | */
|
---|
360 | public ImageProvider setDirs(Collection<String> dirs) {
|
---|
361 | this.dirs = dirs;
|
---|
362 | return this;
|
---|
363 | }
|
---|
364 |
|
---|
365 | /**
|
---|
366 | * Set an id used for caching.
|
---|
367 | * If name starts with <code>http://</code> Id is not used for the cache.
|
---|
368 | * (A URL is unique anyway.)
|
---|
369 | * @param id the id for the cached image
|
---|
370 | * @return the current object, for convenience
|
---|
371 | */
|
---|
372 | public ImageProvider setId(String id) {
|
---|
373 | this.id = id;
|
---|
374 | return this;
|
---|
375 | }
|
---|
376 |
|
---|
377 | /**
|
---|
378 | * Specify a zip file where the image is located.
|
---|
379 | * <p>
|
---|
380 | * (optional)
|
---|
381 | * @param archive zip file where the image is located
|
---|
382 | * @return the current object, for convenience
|
---|
383 | */
|
---|
384 | public ImageProvider setArchive(File archive) {
|
---|
385 | this.archive = archive;
|
---|
386 | return this;
|
---|
387 | }
|
---|
388 |
|
---|
389 | /**
|
---|
390 | * Specify a base path inside the zip file.
|
---|
391 | * <p>
|
---|
392 | * The subdir and name will be relative to this path.
|
---|
393 | * <p>
|
---|
394 | * (optional)
|
---|
395 | * @param inArchiveDir path inside the archive
|
---|
396 | * @return the current object, for convenience
|
---|
397 | */
|
---|
398 | public ImageProvider setInArchiveDir(String inArchiveDir) {
|
---|
399 | this.inArchiveDir = inArchiveDir;
|
---|
400 | return this;
|
---|
401 | }
|
---|
402 |
|
---|
403 | /**
|
---|
404 | * Add an overlay over the image. Multiple overlays are possible.
|
---|
405 | *
|
---|
406 | * @param overlay overlay image and placement specification
|
---|
407 | * @return the current object, for convenience
|
---|
408 | * @since 8095
|
---|
409 | */
|
---|
410 | public ImageProvider addOverlay(ImageOverlay overlay) {
|
---|
411 | if (overlayInfo == null) {
|
---|
412 | overlayInfo = new LinkedList<>();
|
---|
413 | }
|
---|
414 | overlayInfo.add(overlay);
|
---|
415 | return this;
|
---|
416 | }
|
---|
417 |
|
---|
418 | /**
|
---|
419 | * Set the dimensions of the image.
|
---|
420 | * <p>
|
---|
421 | * If not specified, the original size of the image is used.
|
---|
422 | * The width part of the dimension can be -1. Then it will only set the height but
|
---|
423 | * keep the aspect ratio. (And the other way around.)
|
---|
424 | * @param size final dimensions of the image
|
---|
425 | * @return the current object, for convenience
|
---|
426 | */
|
---|
427 | public ImageProvider setSize(Dimension size) {
|
---|
428 | this.virtualWidth = size.width;
|
---|
429 | this.virtualHeight = size.height;
|
---|
430 | return this;
|
---|
431 | }
|
---|
432 |
|
---|
433 | /**
|
---|
434 | * Set the dimensions of the image.
|
---|
435 | * <p>
|
---|
436 | * If not specified, the original size of the image is used.
|
---|
437 | * @param size final dimensions of the image
|
---|
438 | * @return the current object, for convenience
|
---|
439 | * @since 7687
|
---|
440 | */
|
---|
441 | public ImageProvider setSize(ImageSizes size) {
|
---|
442 | return setSize(size.getImageDimension());
|
---|
443 | }
|
---|
444 |
|
---|
445 | /**
|
---|
446 | * Set the dimensions of the image.
|
---|
447 | *
|
---|
448 | * @param width final width of the image
|
---|
449 | * @param height final height of the image
|
---|
450 | * @return the current object, for convenience
|
---|
451 | * @since 10358
|
---|
452 | */
|
---|
453 | public ImageProvider setSize(int width, int height) {
|
---|
454 | this.virtualWidth = width;
|
---|
455 | this.virtualHeight = height;
|
---|
456 | return this;
|
---|
457 | }
|
---|
458 |
|
---|
459 | /**
|
---|
460 | * Set image width
|
---|
461 | * @param width final width of the image
|
---|
462 | * @return the current object, for convenience
|
---|
463 | * @see #setSize
|
---|
464 | */
|
---|
465 | public ImageProvider setWidth(int width) {
|
---|
466 | this.virtualWidth = width;
|
---|
467 | return this;
|
---|
468 | }
|
---|
469 |
|
---|
470 | /**
|
---|
471 | * Set image height
|
---|
472 | * @param height final height of the image
|
---|
473 | * @return the current object, for convenience
|
---|
474 | * @see #setSize
|
---|
475 | */
|
---|
476 | public ImageProvider setHeight(int height) {
|
---|
477 | this.virtualHeight = height;
|
---|
478 | return this;
|
---|
479 | }
|
---|
480 |
|
---|
481 | /**
|
---|
482 | * Limit the maximum size of the image.
|
---|
483 | * <p>
|
---|
484 | * It will shrink the image if necessary, but keep the aspect ratio.
|
---|
485 | * The given width or height can be -1 which means this direction is not bounded.
|
---|
486 | * <p>
|
---|
487 | * 'size' and 'maxSize' are not compatible, you should set only one of them.
|
---|
488 | * @param maxSize maximum image size
|
---|
489 | * @return the current object, for convenience
|
---|
490 | */
|
---|
491 | public ImageProvider setMaxSize(Dimension maxSize) {
|
---|
492 | this.virtualMaxWidth = maxSize.width;
|
---|
493 | this.virtualMaxHeight = maxSize.height;
|
---|
494 | return this;
|
---|
495 | }
|
---|
496 |
|
---|
497 | /**
|
---|
498 | * Limit the maximum size of the image.
|
---|
499 | * <p>
|
---|
500 | * It will shrink the image if necessary, but keep the aspect ratio.
|
---|
501 | * The given width or height can be -1 which means this direction is not bounded.
|
---|
502 | * <p>
|
---|
503 | * This function sets value using the most restrictive of the new or existing set of
|
---|
504 | * values.
|
---|
505 | *
|
---|
506 | * @param maxSize maximum image size
|
---|
507 | * @return the current object, for convenience
|
---|
508 | * @see #setMaxSize(Dimension)
|
---|
509 | */
|
---|
510 | public ImageProvider resetMaxSize(Dimension maxSize) {
|
---|
511 | if (this.virtualMaxWidth == -1 || maxSize.width < this.virtualMaxWidth) {
|
---|
512 | this.virtualMaxWidth = maxSize.width;
|
---|
513 | }
|
---|
514 | if (this.virtualMaxHeight == -1 || maxSize.height < this.virtualMaxHeight) {
|
---|
515 | this.virtualMaxHeight = maxSize.height;
|
---|
516 | }
|
---|
517 | return this;
|
---|
518 | }
|
---|
519 |
|
---|
520 | /**
|
---|
521 | * Limit the maximum size of the image.
|
---|
522 | * <p>
|
---|
523 | * It will shrink the image if necessary, but keep the aspect ratio.
|
---|
524 | * The given width or height can be -1 which means this direction is not bounded.
|
---|
525 | * <p>
|
---|
526 | * 'size' and 'maxSize' are not compatible, you should set only one of them.
|
---|
527 | * @param size maximum image size
|
---|
528 | * @return the current object, for convenience
|
---|
529 | * @since 7687
|
---|
530 | */
|
---|
531 | public ImageProvider setMaxSize(ImageSizes size) {
|
---|
532 | return setMaxSize(size.getImageDimension());
|
---|
533 | }
|
---|
534 |
|
---|
535 | /**
|
---|
536 | * Convenience method, see {@link #setMaxSize(Dimension)}.
|
---|
537 | * @param maxSize maximum image size
|
---|
538 | * @return the current object, for convenience
|
---|
539 | */
|
---|
540 | public ImageProvider setMaxSize(int maxSize) {
|
---|
541 | return this.setMaxSize(new Dimension(maxSize, maxSize));
|
---|
542 | }
|
---|
543 |
|
---|
544 | /**
|
---|
545 | * Limit the maximum width of the image.
|
---|
546 | * @param maxWidth maximum image width
|
---|
547 | * @return the current object, for convenience
|
---|
548 | * @see #setMaxSize
|
---|
549 | */
|
---|
550 | public ImageProvider setMaxWidth(int maxWidth) {
|
---|
551 | this.virtualMaxWidth = maxWidth;
|
---|
552 | return this;
|
---|
553 | }
|
---|
554 |
|
---|
555 | /**
|
---|
556 | * Limit the maximum height of the image.
|
---|
557 | * @param maxHeight maximum image height
|
---|
558 | * @return the current object, for convenience
|
---|
559 | * @see #setMaxSize
|
---|
560 | */
|
---|
561 | public ImageProvider setMaxHeight(int maxHeight) {
|
---|
562 | this.virtualMaxHeight = maxHeight;
|
---|
563 | return this;
|
---|
564 | }
|
---|
565 |
|
---|
566 | /**
|
---|
567 | * Decide, if an exception should be thrown, when the image cannot be located.
|
---|
568 | * <p>
|
---|
569 | * Set to true, when the image URL comes from user data and the image may be missing.
|
---|
570 | *
|
---|
571 | * @param optional true, if JOSM should <b>not</b> throw a RuntimeException
|
---|
572 | * in case the image cannot be located.
|
---|
573 | * @return the current object, for convenience
|
---|
574 | */
|
---|
575 | public ImageProvider setOptional(boolean optional) {
|
---|
576 | this.optional = optional;
|
---|
577 | return this;
|
---|
578 | }
|
---|
579 |
|
---|
580 | /**
|
---|
581 | * Suppresses warning on the command line in case the image cannot be found.
|
---|
582 | * <p>
|
---|
583 | * In combination with setOptional(true);
|
---|
584 | * @param suppressWarnings if <code>true</code> warnings are suppressed
|
---|
585 | * @return the current object, for convenience
|
---|
586 | */
|
---|
587 | public ImageProvider setSuppressWarnings(boolean suppressWarnings) {
|
---|
588 | this.suppressWarnings = suppressWarnings;
|
---|
589 | return this;
|
---|
590 | }
|
---|
591 |
|
---|
592 | /**
|
---|
593 | * Set, if image must be filtered to grayscale so it will look like disabled icon.
|
---|
594 | *
|
---|
595 | * @param disabled true, if image must be grayed out for disabled state
|
---|
596 | * @return the current object, for convenience
|
---|
597 | * @since 10428
|
---|
598 | */
|
---|
599 | public ImageProvider setDisabled(boolean disabled) {
|
---|
600 | this.isDisabled = disabled;
|
---|
601 | return this;
|
---|
602 | }
|
---|
603 |
|
---|
604 | /**
|
---|
605 | * Decide, if multi-resolution image is requested (default <code>true</code>).
|
---|
606 | * <p>
|
---|
607 | * A <code>java.awt.image.MultiResolutionImage</code> is a Java 9 {@link Image}
|
---|
608 | * implementation, which adds support for HiDPI displays. The effect will be
|
---|
609 | * that in HiDPI mode, when GUI elements are scaled by a factor 1.5, 2.0, etc.,
|
---|
610 | * the images are not just up-scaled, but a higher resolution version of the image is rendered instead.
|
---|
611 | * <p>
|
---|
612 | * Use {@link HiDPISupport#getBaseImage(java.awt.Image)} to extract the original image from a multi-resolution image.
|
---|
613 | * <p>
|
---|
614 | * See {@link HiDPISupport#processMRImage} for how to process the image without removing the multi-resolution magic.
|
---|
615 | * @param multiResolution true, if multi-resolution image is requested
|
---|
616 | * @return the current object, for convenience
|
---|
617 | */
|
---|
618 | public ImageProvider setMultiResolution(boolean multiResolution) {
|
---|
619 | this.multiResolution = multiResolution;
|
---|
620 | return this;
|
---|
621 | }
|
---|
622 |
|
---|
623 | /**
|
---|
624 | * Determines if this icon is located on a remote location (http, https, wiki).
|
---|
625 | * @return {@code true} if this icon is located on a remote location (http, https, wiki)
|
---|
626 | * @since 13250
|
---|
627 | */
|
---|
628 | public boolean isRemote() {
|
---|
629 | return name.startsWith(HTTP_PROTOCOL) || name.startsWith(HTTPS_PROTOCOL) || name.startsWith(WIKI_PROTOCOL);
|
---|
630 | }
|
---|
631 |
|
---|
632 | /**
|
---|
633 | * Execute the image request and scale result.
|
---|
634 | * @return the requested image or null if the request failed
|
---|
635 | */
|
---|
636 | public ImageIcon get() {
|
---|
637 | ImageResource ir = getResource();
|
---|
638 |
|
---|
639 | if (ir == null) {
|
---|
640 | return null;
|
---|
641 | } else if (Logging.isTraceEnabled()) {
|
---|
642 | Logging.trace("get {0} from {1}", this, Thread.currentThread());
|
---|
643 | }
|
---|
644 | if (virtualMaxWidth != -1 || virtualMaxHeight != -1)
|
---|
645 | return ir.getImageIcon(new Dimension(virtualMaxWidth, virtualMaxHeight), multiResolution, null);
|
---|
646 | else
|
---|
647 | return ir.getImageIcon(new Dimension(virtualWidth, virtualHeight), multiResolution, ImageResizeMode.AUTO);
|
---|
648 | }
|
---|
649 |
|
---|
650 | /**
|
---|
651 | * Execute the image request and scale result.
|
---|
652 | * @return the requested image as data: URL or null if the request failed
|
---|
653 | * @since 16872
|
---|
654 | */
|
---|
655 | public String getDataURL() {
|
---|
656 | ImageIcon ii = get();
|
---|
657 | if (ii != null) {
|
---|
658 | final ByteArrayOutputStream os = new ByteArrayOutputStream();
|
---|
659 | try {
|
---|
660 | Image i = ii.getImage();
|
---|
661 | if (i instanceof RenderedImage) {
|
---|
662 | ImageIO.write((RenderedImage) i, "png", os);
|
---|
663 | return "data:image/png;base64," + Base64.getEncoder().encodeToString(os.toByteArray());
|
---|
664 | }
|
---|
665 | } catch (final IOException ioe) {
|
---|
666 | return null;
|
---|
667 | }
|
---|
668 | }
|
---|
669 | return null;
|
---|
670 | }
|
---|
671 |
|
---|
672 | /**
|
---|
673 | * Load the image in a background thread.
|
---|
674 | * <p>
|
---|
675 | * This method returns immediately and runs the image request asynchronously.
|
---|
676 | * @param action the action that will deal with the image
|
---|
677 | *
|
---|
678 | * @return the future of the requested image
|
---|
679 | * @since 13252
|
---|
680 | */
|
---|
681 | public CompletableFuture<Void> getAsync(Consumer<? super ImageIcon> action) {
|
---|
682 | return isRemote()
|
---|
683 | ? CompletableFuture.supplyAsync(this::get, IMAGE_FETCHER).thenAcceptAsync(action, IMAGE_FETCHER)
|
---|
684 | : CompletableFuture.completedFuture(get()).thenAccept(action);
|
---|
685 | }
|
---|
686 |
|
---|
687 | /**
|
---|
688 | * Execute the image request.
|
---|
689 | *
|
---|
690 | * @return the requested image or null if the request failed
|
---|
691 | * @since 7693
|
---|
692 | */
|
---|
693 | public ImageResource getResource() {
|
---|
694 | ImageResource ir = getIfAvailableImpl();
|
---|
695 | if (ir == null) {
|
---|
696 | if (!optional) {
|
---|
697 | String ext = name.indexOf('.') != -1 ? "" : ".???";
|
---|
698 | throw new JosmRuntimeException(
|
---|
699 | tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.",
|
---|
700 | name + ext));
|
---|
701 | } else {
|
---|
702 | if (!suppressWarnings) {
|
---|
703 | Logging.error(tr("Failed to locate image ''{0}''", name));
|
---|
704 | }
|
---|
705 | return null;
|
---|
706 | }
|
---|
707 | }
|
---|
708 | if (overlayInfo != null) {
|
---|
709 | ir = new ImageResource(ir, overlayInfo);
|
---|
710 | }
|
---|
711 | if (isDisabled) {
|
---|
712 | ir.setDisabled(true);
|
---|
713 | }
|
---|
714 | return ir;
|
---|
715 | }
|
---|
716 |
|
---|
717 | /**
|
---|
718 | * Load the image in a background thread.
|
---|
719 | * <p>
|
---|
720 | * This method returns immediately and runs the image request asynchronously.
|
---|
721 | * @param action the action that will deal with the image
|
---|
722 | *
|
---|
723 | * @return the future of the requested image
|
---|
724 | * @since 13252
|
---|
725 | */
|
---|
726 | public CompletableFuture<Void> getResourceAsync(Consumer<? super ImageResource> action) {
|
---|
727 | return isRemote()
|
---|
728 | ? CompletableFuture.supplyAsync(this::getResource, IMAGE_FETCHER).thenAcceptAsync(action, IMAGE_FETCHER)
|
---|
729 | : CompletableFuture.completedFuture(getResource()).thenAccept(action);
|
---|
730 | }
|
---|
731 |
|
---|
732 | /**
|
---|
733 | * Load an image with a given file name.
|
---|
734 | *
|
---|
735 | * @param subdir subdirectory the image lies in
|
---|
736 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
737 | * @return The requested Image.
|
---|
738 | * @throws RuntimeException if the image cannot be located
|
---|
739 | */
|
---|
740 | public static ImageIcon get(String subdir, String name) {
|
---|
741 | return new ImageProvider(subdir, name).get();
|
---|
742 | }
|
---|
743 |
|
---|
744 | /**
|
---|
745 | * Load an image with a given file name.
|
---|
746 | *
|
---|
747 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
748 | * @return the requested image or null if the request failed
|
---|
749 | * @see #get(String, String)
|
---|
750 | */
|
---|
751 | public static ImageIcon get(String name) {
|
---|
752 | return new ImageProvider(name).get();
|
---|
753 | }
|
---|
754 |
|
---|
755 | /**
|
---|
756 | * Load an image from directory with a given file name and size.
|
---|
757 | *
|
---|
758 | * @param subdir subdirectory the image lies in
|
---|
759 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
760 | * @param size Target icon size
|
---|
761 | * @return The requested Image.
|
---|
762 | * @throws RuntimeException if the image cannot be located
|
---|
763 | * @since 10428
|
---|
764 | */
|
---|
765 | public static ImageIcon get(String subdir, String name, ImageSizes size) {
|
---|
766 | return new ImageProvider(subdir, name).setSize(size).get();
|
---|
767 | }
|
---|
768 |
|
---|
769 | /**
|
---|
770 | * Load an empty image with a given size.
|
---|
771 | *
|
---|
772 | * @param size Target icon size
|
---|
773 | * @return The requested Image.
|
---|
774 | * @since 10358
|
---|
775 | */
|
---|
776 | public static ImageIcon getEmpty(ImageSizes size) {
|
---|
777 | Dimension iconRealSize = GuiSizesHelper.getDimensionDpiAdjusted(size.getImageDimension());
|
---|
778 | return new ImageIcon(new BufferedImage(iconRealSize.width, iconRealSize.height,
|
---|
779 | BufferedImage.TYPE_INT_ARGB));
|
---|
780 | }
|
---|
781 |
|
---|
782 | /**
|
---|
783 | * Load an image with a given file name, but do not throw an exception
|
---|
784 | * when the image cannot be found.
|
---|
785 | *
|
---|
786 | * @param subdir subdirectory the image lies in
|
---|
787 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
788 | * @return the requested image or null if the request failed
|
---|
789 | * @see #get(String, String)
|
---|
790 | */
|
---|
791 | public static ImageIcon getIfAvailable(String subdir, String name) {
|
---|
792 | return new ImageProvider(subdir, name).setOptional(true).get();
|
---|
793 | }
|
---|
794 |
|
---|
795 | /**
|
---|
796 | * Load an image with a given file name and size.
|
---|
797 | *
|
---|
798 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
799 | * @param size Target icon size
|
---|
800 | * @return the requested image or null if the request failed
|
---|
801 | * @see #get(String, String)
|
---|
802 | * @since 10428
|
---|
803 | */
|
---|
804 | public static ImageIcon get(String name, ImageSizes size) {
|
---|
805 | return new ImageProvider(name).setSize(size).get();
|
---|
806 | }
|
---|
807 |
|
---|
808 | /**
|
---|
809 | * Load an image with a given file name, but do not throw an exception
|
---|
810 | * when the image cannot be found.
|
---|
811 | *
|
---|
812 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
813 | * @return the requested image or null if the request failed
|
---|
814 | * @see #getIfAvailable(String, String)
|
---|
815 | */
|
---|
816 | public static ImageIcon getIfAvailable(String name) {
|
---|
817 | return new ImageProvider(name).setOptional(true).get();
|
---|
818 | }
|
---|
819 |
|
---|
820 | /**
|
---|
821 | * {@code data:[<mediatype>][;base64],<data>}
|
---|
822 | * @see <a href="http://tools.ietf.org/html/rfc2397">RFC2397</a>
|
---|
823 | */
|
---|
824 | private static final Pattern dataUrlPattern = Pattern.compile(
|
---|
825 | "^data:([a-zA-Z]+/[a-zA-Z+]+)?(;base64)?,(.+)$");
|
---|
826 |
|
---|
827 | /**
|
---|
828 | * Clears the internal image caches.
|
---|
829 | * @since 11021
|
---|
830 | */
|
---|
831 | public static void clearCache() {
|
---|
832 | cache.clear();
|
---|
833 | synchronized (osmPrimitiveTypeCache) {
|
---|
834 | osmPrimitiveTypeCache.clear();
|
---|
835 | }
|
---|
836 | }
|
---|
837 |
|
---|
838 | /**
|
---|
839 | * Internal implementation of the image request.
|
---|
840 | *
|
---|
841 | * @return the requested image or null if the request failed
|
---|
842 | */
|
---|
843 | private ImageResource getIfAvailableImpl() {
|
---|
844 | // This method is called from different thread and modifying HashMap concurrently can result
|
---|
845 | // for example in loops in map entries (ie freeze when such entry is retrieved)
|
---|
846 |
|
---|
847 | String prefix = isDisabled ? "dis:" : "";
|
---|
848 | if (name.startsWith("data:")) {
|
---|
849 | String url = name;
|
---|
850 | ImageResource ir = cache.get(prefix + url);
|
---|
851 | if (ir != null) return ir;
|
---|
852 | ir = getIfAvailableDataUrl(url);
|
---|
853 | if (ir != null) {
|
---|
854 | cache.put(prefix + url, ir);
|
---|
855 | }
|
---|
856 | return ir;
|
---|
857 | }
|
---|
858 |
|
---|
859 | ImageType type = Utils.hasExtension(name, "svg") ? ImageType.SVG : ImageType.OTHER;
|
---|
860 |
|
---|
861 | if (name.startsWith(HTTP_PROTOCOL) || name.startsWith(HTTPS_PROTOCOL)) {
|
---|
862 | String url = name;
|
---|
863 | ImageResource ir = cache.get(prefix + url);
|
---|
864 | if (ir != null) return ir;
|
---|
865 | ir = getIfAvailableHttp(url, type);
|
---|
866 | if (ir != null) {
|
---|
867 | cache.put(prefix + url, ir);
|
---|
868 | }
|
---|
869 | return ir;
|
---|
870 | } else if (name.startsWith(WIKI_PROTOCOL)) {
|
---|
871 | ImageResource ir = cache.get(prefix + name);
|
---|
872 | if (ir != null) return ir;
|
---|
873 | ir = getIfAvailableWiki(name, type);
|
---|
874 | if (ir != null) {
|
---|
875 | cache.put(prefix + name, ir);
|
---|
876 | }
|
---|
877 | return ir;
|
---|
878 | }
|
---|
879 |
|
---|
880 | if (subdir == null) {
|
---|
881 | subdir = "";
|
---|
882 | } else if (!subdir.isEmpty() && !subdir.endsWith("/")) {
|
---|
883 | subdir += '/';
|
---|
884 | }
|
---|
885 | String[] extensions;
|
---|
886 | if (name.indexOf('.') != -1) {
|
---|
887 | extensions = new String[] {""};
|
---|
888 | } else {
|
---|
889 | extensions = new String[] {".png", ".svg"};
|
---|
890 | }
|
---|
891 | for (ImageLocations place : ImageLocations.values()) {
|
---|
892 | for (String ext : extensions) {
|
---|
893 |
|
---|
894 | if (".svg".equals(ext)) {
|
---|
895 | type = ImageType.SVG;
|
---|
896 | } else if (".png".equals(ext)) {
|
---|
897 | type = ImageType.OTHER;
|
---|
898 | }
|
---|
899 |
|
---|
900 | String fullName = subdir + name + ext;
|
---|
901 | String cacheName = prefix + fullName;
|
---|
902 | /* cache separately */
|
---|
903 | if (!Utils.isEmpty(dirs)) {
|
---|
904 | cacheName = "id:" + id + ':' + fullName;
|
---|
905 | if (archive != null) {
|
---|
906 | cacheName += ':' + archive.getName();
|
---|
907 | }
|
---|
908 | }
|
---|
909 |
|
---|
910 | switch (place) {
|
---|
911 | case ARCHIVE:
|
---|
912 | if (archive != null) {
|
---|
913 | cacheName = "zip:" + archive.hashCode() + ':' + cacheName;
|
---|
914 | ImageResource ir = cache.get(cacheName);
|
---|
915 | if (ir != null) return ir;
|
---|
916 |
|
---|
917 | ir = getIfAvailableZip(fullName, archive, inArchiveDir, type);
|
---|
918 | if (ir != null) {
|
---|
919 | cache.put(cacheName, ir);
|
---|
920 | return ir;
|
---|
921 | }
|
---|
922 | }
|
---|
923 | break;
|
---|
924 | case LOCAL:
|
---|
925 | ImageResource ir = cache.get(cacheName);
|
---|
926 | if (ir != null) return ir;
|
---|
927 |
|
---|
928 | // getImageUrl() does a ton of "stat()" calls and gets expensive
|
---|
929 | // and redundant when you have a whole ton of objects. So,
|
---|
930 | // index the cache by the name of the icon we're looking for
|
---|
931 | // and don't bother to create a URL unless we're actually creating the image.
|
---|
932 | URL path = getImageUrl(fullName);
|
---|
933 | if (path == null) {
|
---|
934 | continue;
|
---|
935 | }
|
---|
936 | ir = getIfAvailableLocalURL(path, type);
|
---|
937 | if (ir != null) {
|
---|
938 | cache.put(cacheName, ir);
|
---|
939 | return ir;
|
---|
940 | }
|
---|
941 | break;
|
---|
942 | }
|
---|
943 | }
|
---|
944 | }
|
---|
945 | return null;
|
---|
946 | }
|
---|
947 |
|
---|
948 | /**
|
---|
949 | * Internal implementation of the image request for URL's.
|
---|
950 | *
|
---|
951 | * @param url URL of the image
|
---|
952 | * @param type data type of the image
|
---|
953 | * @return the requested image or null if the request failed
|
---|
954 | */
|
---|
955 | private static ImageResource getIfAvailableHttp(String url, ImageType type) {
|
---|
956 | try (CachedFile cf = new CachedFile(url).setDestDir(
|
---|
957 | new File(Config.getDirs().getCacheDirectory(true), "images").getPath());
|
---|
958 | InputStream is = cf.getInputStream()) {
|
---|
959 | switch (type) {
|
---|
960 | case SVG:
|
---|
961 | SVGDiagram svg;
|
---|
962 | synchronized (getSvgUniverse()) {
|
---|
963 | URI uri = getSvgUniverse().loadSVG(is, Utils.fileToURL(cf.getFile()).toString());
|
---|
964 | svg = getSvgUniverse().getDiagram(uri);
|
---|
965 | }
|
---|
966 | return svg == null ? null : new ImageResource(svg);
|
---|
967 | case OTHER:
|
---|
968 | BufferedImage img = null;
|
---|
969 | try {
|
---|
970 | img = read(Utils.fileToURL(cf.getFile()), false, false);
|
---|
971 | } catch (IOException | UnsatisfiedLinkError e) {
|
---|
972 | Logging.log(Logging.LEVEL_WARN, "Exception while reading HTTP image:", e);
|
---|
973 | }
|
---|
974 | return img == null ? null : new ImageResource(img);
|
---|
975 | }
|
---|
976 | } catch (IOException e) {
|
---|
977 | Logging.debug(e);
|
---|
978 | return null;
|
---|
979 | }
|
---|
980 | throw new AssertionError("Unsupported type: " + type);
|
---|
981 | }
|
---|
982 |
|
---|
983 | /**
|
---|
984 | * Internal implementation of the image request for inline images (<b>data:</b> urls).
|
---|
985 | *
|
---|
986 | * @param url the data URL for image extraction
|
---|
987 | * @return the requested image or null if the request failed
|
---|
988 | */
|
---|
989 | private static ImageResource getIfAvailableDataUrl(String url) {
|
---|
990 | Matcher m = dataUrlPattern.matcher(url);
|
---|
991 | if (m.matches()) {
|
---|
992 | String base64 = m.group(2);
|
---|
993 | String data = m.group(3);
|
---|
994 | byte[] bytes;
|
---|
995 | try {
|
---|
996 | if (";base64".equals(base64)) {
|
---|
997 | bytes = Base64.getDecoder().decode(data);
|
---|
998 | } else {
|
---|
999 | bytes = Utils.decodeUrl(data).getBytes(StandardCharsets.UTF_8);
|
---|
1000 | }
|
---|
1001 | } catch (IllegalArgumentException ex) {
|
---|
1002 | Logging.log(Logging.LEVEL_WARN, "Unable to decode URL data part: "+ex.getMessage() + " (" + data + ')', ex);
|
---|
1003 | return null;
|
---|
1004 | }
|
---|
1005 | String mediatype = m.group(1);
|
---|
1006 | if ("image/svg+xml".equals(mediatype)) {
|
---|
1007 | String s = new String(bytes, StandardCharsets.UTF_8);
|
---|
1008 | // see #19097: check if s starts with PNG magic
|
---|
1009 | if (s.length() > 4 && "PNG".equals(s.substring(1, 4))) {
|
---|
1010 | Logging.warn("url contains PNG file " + url);
|
---|
1011 | return null;
|
---|
1012 | }
|
---|
1013 | SVGDiagram svg;
|
---|
1014 | synchronized (getSvgUniverse()) {
|
---|
1015 | URI uri = getSvgUniverse().loadSVG(new StringReader(s), Utils.encodeUrl(s));
|
---|
1016 | svg = getSvgUniverse().getDiagram(uri);
|
---|
1017 | }
|
---|
1018 | if (svg == null) {
|
---|
1019 | Logging.warn("Unable to process svg: "+s);
|
---|
1020 | return null;
|
---|
1021 | }
|
---|
1022 | return new ImageResource(svg);
|
---|
1023 | } else {
|
---|
1024 | try {
|
---|
1025 | // See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
|
---|
1026 | // This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
|
---|
1027 | // CHECKSTYLE.OFF: LineLength
|
---|
1028 | // hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/dc4322602480/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
|
---|
1029 | // CHECKSTYLE.ON: LineLength
|
---|
1030 | Image img = read(new ByteArrayInputStream(bytes), false, true);
|
---|
1031 | return img == null ? null : new ImageResource(img);
|
---|
1032 | } catch (IOException | UnsatisfiedLinkError e) {
|
---|
1033 | Logging.log(Logging.LEVEL_WARN, "Exception while reading image:", e);
|
---|
1034 | }
|
---|
1035 | }
|
---|
1036 | }
|
---|
1037 | return null;
|
---|
1038 | }
|
---|
1039 |
|
---|
1040 | /**
|
---|
1041 | * Internal implementation of the image request for wiki images.
|
---|
1042 | *
|
---|
1043 | * @param name image file name
|
---|
1044 | * @param type data type of the image
|
---|
1045 | * @return the requested image or null if the request failed
|
---|
1046 | */
|
---|
1047 | private static ImageResource getIfAvailableWiki(String name, ImageType type) {
|
---|
1048 | final List<String> defaultBaseUrls = Arrays.asList(
|
---|
1049 | "https://wiki.openstreetmap.org/w/images/",
|
---|
1050 | "https://upload.wikimedia.org/wikipedia/commons/",
|
---|
1051 | "https://wiki.openstreetmap.org/wiki/File:"
|
---|
1052 | );
|
---|
1053 | final Collection<String> baseUrls = Config.getPref().getList("image-provider.wiki.urls", defaultBaseUrls);
|
---|
1054 |
|
---|
1055 | final String fn = name.substring(name.lastIndexOf('/') + 1);
|
---|
1056 |
|
---|
1057 | ImageResource result = null;
|
---|
1058 | for (String b : baseUrls) {
|
---|
1059 | String url;
|
---|
1060 | if (b.endsWith(":")) {
|
---|
1061 | url = getImgUrlFromWikiInfoPage(b, fn);
|
---|
1062 | if (url == null) {
|
---|
1063 | continue;
|
---|
1064 | }
|
---|
1065 | } else {
|
---|
1066 | url = Mediawiki.getImageUrl(b, fn);
|
---|
1067 | }
|
---|
1068 | result = getIfAvailableHttp(url, type);
|
---|
1069 | if (result != null) {
|
---|
1070 | break;
|
---|
1071 | }
|
---|
1072 | }
|
---|
1073 | return result;
|
---|
1074 | }
|
---|
1075 |
|
---|
1076 | /**
|
---|
1077 | * Internal implementation of the image request for images in Zip archives.
|
---|
1078 | *
|
---|
1079 | * @param fullName image file name
|
---|
1080 | * @param archive the archive to get image from
|
---|
1081 | * @param inArchiveDir directory of the image inside the archive or <code>null</code>
|
---|
1082 | * @param type data type of the image
|
---|
1083 | * @return the requested image or null if the request failed
|
---|
1084 | */
|
---|
1085 | private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
|
---|
1086 | Objects.requireNonNull(type, "ImageType must not be null");
|
---|
1087 | try (ZipFile zipFile = new ZipFile(archive, StandardCharsets.UTF_8)) {
|
---|
1088 | if (inArchiveDir == null || ".".equals(inArchiveDir)) {
|
---|
1089 | inArchiveDir = "";
|
---|
1090 | } else if (!inArchiveDir.isEmpty()) {
|
---|
1091 | inArchiveDir += '/';
|
---|
1092 | }
|
---|
1093 | String entryName = inArchiveDir + fullName;
|
---|
1094 | ZipEntry entry = zipFile.getEntry(entryName);
|
---|
1095 | if (entry != null) {
|
---|
1096 | int size = (int) entry.getSize();
|
---|
1097 | int offs = 0;
|
---|
1098 | byte[] buf = new byte[size];
|
---|
1099 | try (InputStream is = zipFile.getInputStream(entry)) {
|
---|
1100 | switch (type) {
|
---|
1101 | case SVG:
|
---|
1102 | SVGDiagram svg;
|
---|
1103 | synchronized (getSvgUniverse()) {
|
---|
1104 | URI uri = getSvgUniverse().loadSVG(is, entryName, true);
|
---|
1105 | svg = getSvgUniverse().getDiagram(uri);
|
---|
1106 | }
|
---|
1107 | return svg == null ? null : new ImageResource(svg);
|
---|
1108 | case OTHER:
|
---|
1109 | while (size > 0) {
|
---|
1110 | int l = is.read(buf, offs, size);
|
---|
1111 | offs += l;
|
---|
1112 | size -= l;
|
---|
1113 | }
|
---|
1114 | BufferedImage img = null;
|
---|
1115 | try {
|
---|
1116 | img = read(new ByteArrayInputStream(buf), false, false);
|
---|
1117 | } catch (IOException | UnsatisfiedLinkError e) {
|
---|
1118 | Logging.warn(e);
|
---|
1119 | }
|
---|
1120 | return img == null ? null : new ImageResource(img);
|
---|
1121 | }
|
---|
1122 | }
|
---|
1123 | }
|
---|
1124 | } catch (IOException | UnsatisfiedLinkError e) {
|
---|
1125 | Logging.log(Logging.LEVEL_WARN, tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()), e);
|
---|
1126 | }
|
---|
1127 | return null;
|
---|
1128 | }
|
---|
1129 |
|
---|
1130 | /**
|
---|
1131 | * Internal implementation of the image request for local images.
|
---|
1132 | *
|
---|
1133 | * @param path image file path
|
---|
1134 | * @param type data type of the image
|
---|
1135 | * @return the requested image or null if the request failed
|
---|
1136 | */
|
---|
1137 | private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
|
---|
1138 | Objects.requireNonNull(type, "ImageType must not be null");
|
---|
1139 | switch (type) {
|
---|
1140 | case SVG:
|
---|
1141 | SVGDiagram svg = null;
|
---|
1142 | synchronized (getSvgUniverse()) {
|
---|
1143 | try {
|
---|
1144 | URI uri = null;
|
---|
1145 | try {
|
---|
1146 | uri = getSvgUniverse().loadSVG(path);
|
---|
1147 | } catch (InvalidPathException e) {
|
---|
1148 | Logging.error("Cannot open {0}: {1}", path, e.getMessage());
|
---|
1149 | Logging.trace(e);
|
---|
1150 | }
|
---|
1151 | if (uri == null && "jar".equals(path.getProtocol())) {
|
---|
1152 | URL betterPath = Utils.betterJarUrl(path);
|
---|
1153 | if (betterPath != null) {
|
---|
1154 | uri = getSvgUniverse().loadSVG(betterPath);
|
---|
1155 | }
|
---|
1156 | }
|
---|
1157 | svg = getSvgUniverse().getDiagram(uri);
|
---|
1158 | } catch (SecurityException | IOException e) {
|
---|
1159 | Logging.log(Logging.LEVEL_WARN, "Unable to read SVG", e);
|
---|
1160 | }
|
---|
1161 | }
|
---|
1162 | return svg == null ? null : new ImageResource(svg);
|
---|
1163 | case OTHER:
|
---|
1164 | BufferedImage img = null;
|
---|
1165 | try {
|
---|
1166 | // See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
|
---|
1167 | // This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
|
---|
1168 | // hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/dc4322602480/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
|
---|
1169 | img = read(path, false, true);
|
---|
1170 | if (Logging.isDebugEnabled() && isTransparencyForced(img)) {
|
---|
1171 | Logging.debug("Transparency has been forced for image {0}", path);
|
---|
1172 | }
|
---|
1173 | } catch (IOException | UnsatisfiedLinkError e) {
|
---|
1174 | Logging.log(Logging.LEVEL_WARN, "Unable to read image", e);
|
---|
1175 | Logging.debug(e);
|
---|
1176 | }
|
---|
1177 | return img == null ? null : new ImageResource(img);
|
---|
1178 | }
|
---|
1179 | // Default
|
---|
1180 | throw new AssertionError();
|
---|
1181 | }
|
---|
1182 |
|
---|
1183 | private static URL getImageUrl(String path, String name) {
|
---|
1184 | if (path != null && path.startsWith("resource://")) {
|
---|
1185 | return ResourceProvider.getResource(path.substring("resource://".length()) + name);
|
---|
1186 | } else {
|
---|
1187 | File f = new File(path, name);
|
---|
1188 | try {
|
---|
1189 | if ((path != null || f.isAbsolute()) && f.exists())
|
---|
1190 | return Utils.fileToURL(f);
|
---|
1191 | } catch (SecurityException e) {
|
---|
1192 | Logging.log(Logging.LEVEL_ERROR, "Unable to access image", e);
|
---|
1193 | }
|
---|
1194 | }
|
---|
1195 | return null;
|
---|
1196 | }
|
---|
1197 |
|
---|
1198 | private URL getImageUrl(String imageName) {
|
---|
1199 | URL u;
|
---|
1200 |
|
---|
1201 | // Try passed directories first
|
---|
1202 | if (dirs != null) {
|
---|
1203 | for (String name : dirs) {
|
---|
1204 | try {
|
---|
1205 | u = getImageUrl(name, imageName);
|
---|
1206 | if (u != null)
|
---|
1207 | return u;
|
---|
1208 | } catch (SecurityException e) {
|
---|
1209 | Logging.log(Logging.LEVEL_WARN, tr(
|
---|
1210 | "Failed to access directory ''{0}'' for security reasons. Exception was: {1}",
|
---|
1211 | name, e.toString()), e);
|
---|
1212 | }
|
---|
1213 |
|
---|
1214 | }
|
---|
1215 | }
|
---|
1216 | // Try user-data directory
|
---|
1217 | if (Config.getDirs() != null) {
|
---|
1218 | File file = new File(Config.getDirs().getUserDataDirectory(false), "images");
|
---|
1219 | String dir = file.getPath();
|
---|
1220 | try {
|
---|
1221 | dir = file.getAbsolutePath();
|
---|
1222 | } catch (SecurityException e) {
|
---|
1223 | Logging.debug(e);
|
---|
1224 | }
|
---|
1225 | try {
|
---|
1226 | u = getImageUrl(dir, imageName);
|
---|
1227 | if (u != null)
|
---|
1228 | return u;
|
---|
1229 | } catch (SecurityException e) {
|
---|
1230 | Logging.log(Logging.LEVEL_WARN, tr(
|
---|
1231 | "Failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
|
---|
1232 | .toString()), e);
|
---|
1233 | }
|
---|
1234 | }
|
---|
1235 |
|
---|
1236 | // Absolute path?
|
---|
1237 | u = getImageUrl(null, imageName);
|
---|
1238 | if (u != null)
|
---|
1239 | return u;
|
---|
1240 |
|
---|
1241 | // Try plugins and josm classloader
|
---|
1242 | u = getImageUrl("resource://images/", imageName);
|
---|
1243 | if (u != null)
|
---|
1244 | return u;
|
---|
1245 |
|
---|
1246 | // Try all other resource directories
|
---|
1247 | for (String location : Preferences.getAllPossiblePreferenceDirs()) {
|
---|
1248 | u = getImageUrl(location + "images", imageName);
|
---|
1249 | if (u != null)
|
---|
1250 | return u;
|
---|
1251 | u = getImageUrl(location, imageName);
|
---|
1252 | if (u != null)
|
---|
1253 | return u;
|
---|
1254 | }
|
---|
1255 |
|
---|
1256 | return null;
|
---|
1257 | }
|
---|
1258 |
|
---|
1259 | /**
|
---|
1260 | * Reads the wiki page on a certain file in html format in order to find the real image URL.
|
---|
1261 | *
|
---|
1262 | * @param base base URL for Wiki image
|
---|
1263 | * @param fn filename of the Wiki image
|
---|
1264 | * @return image URL for a Wiki image or null in case of error
|
---|
1265 | */
|
---|
1266 | private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
|
---|
1267 | try {
|
---|
1268 | final XMLReader parser = XmlUtils.newSafeSAXParser().getXMLReader();
|
---|
1269 | parser.setContentHandler(new DefaultHandler() {
|
---|
1270 | @Override
|
---|
1271 | public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
|
---|
1272 | if ("img".equalsIgnoreCase(localName)) {
|
---|
1273 | String val = atts.getValue("src");
|
---|
1274 | if (val.endsWith(fn))
|
---|
1275 | throw new SAXReturnException(val); // parsing done, quit early
|
---|
1276 | }
|
---|
1277 | }
|
---|
1278 | });
|
---|
1279 |
|
---|
1280 | parser.setEntityResolver((publicId, systemId) -> new InputSource(new ByteArrayInputStream(new byte[0])));
|
---|
1281 |
|
---|
1282 | try (CachedFile cf = new CachedFile(base + fn).setDestDir(
|
---|
1283 | new File(Config.getDirs().getUserDataDirectory(true), "images").getPath());
|
---|
1284 | InputStream is = cf.getInputStream()) {
|
---|
1285 | parser.parse(new InputSource(is));
|
---|
1286 | }
|
---|
1287 | } catch (SAXReturnException e) {
|
---|
1288 | Logging.trace(e);
|
---|
1289 | return e.getResult();
|
---|
1290 | } catch (IOException | SAXException | ParserConfigurationException e) {
|
---|
1291 | Logging.warn("Parsing " + base + fn + " failed:\n" + e);
|
---|
1292 | return null;
|
---|
1293 | }
|
---|
1294 | Logging.warn("Parsing " + base + fn + " failed: Unexpected content.");
|
---|
1295 | return null;
|
---|
1296 | }
|
---|
1297 |
|
---|
1298 | /**
|
---|
1299 | * Load a cursor with a given file name, optionally decorated with an overlay image.
|
---|
1300 | *
|
---|
1301 | * @param name the cursor image filename in "cursor" directory
|
---|
1302 | * @param overlay optional overlay image
|
---|
1303 | * @return cursor with a given file name, optionally decorated with an overlay image
|
---|
1304 | */
|
---|
1305 | public static Cursor getCursor(String name, String overlay) {
|
---|
1306 | if (GraphicsEnvironment.isHeadless()) {
|
---|
1307 | Logging.debug("Cursors are not available in headless mode. Returning null for ''{0}''", name);
|
---|
1308 | return null;
|
---|
1309 | }
|
---|
1310 |
|
---|
1311 | Point hotSpot = new Point();
|
---|
1312 | Image image = getCursorImage(name, overlay, dim -> Toolkit.getDefaultToolkit().getBestCursorSize(dim.width, dim.height), hotSpot);
|
---|
1313 |
|
---|
1314 | return Toolkit.getDefaultToolkit().createCustomCursor(image, hotSpot, name);
|
---|
1315 | }
|
---|
1316 |
|
---|
1317 | /**
|
---|
1318 | * The cursor hotspot constants {@link #DEFAULT_HOTSPOT} and {@link #CROSSHAIR_HOTSPOT} are relative to this cursor size
|
---|
1319 | */
|
---|
1320 | protected static final int CURSOR_SIZE_HOTSPOT_IS_RELATIVE_TO = 32;
|
---|
1321 | private static final Point DEFAULT_HOTSPOT = new Point(3, 2); // FIXME: define better hotspot for rotate.png
|
---|
1322 | private static final Point CROSSHAIR_HOTSPOT = new Point(10, 10);
|
---|
1323 |
|
---|
1324 | /**
|
---|
1325 | * Load a cursor image with a given file name, optionally decorated with an overlay image
|
---|
1326 | *
|
---|
1327 | * @param name the cursor image filename in "cursor" directory
|
---|
1328 | * @param overlay optional overlay image
|
---|
1329 | * @param bestCursorSizeFunction computes the best cursor size, see {@link Toolkit#getBestCursorSize(int, int)}
|
---|
1330 | * @param hotSpot will be set to the properly scaled hotspot of the cursor
|
---|
1331 | * @return cursor with a given file name, optionally decorated with an overlay image
|
---|
1332 | */
|
---|
1333 | static Image getCursorImage(String name, String overlay, UnaryOperator<Dimension> bestCursorSizeFunction, /* out */ Point hotSpot) {
|
---|
1334 | ImageProvider imageProvider = new ImageProvider("cursor", name);
|
---|
1335 | if (overlay != null) {
|
---|
1336 | imageProvider
|
---|
1337 | .setMaxSize(ImageSizes.CURSOR)
|
---|
1338 | .addOverlay(new ImageOverlay(new ImageProvider("cursor/modifier/" + overlay)
|
---|
1339 | .setMaxSize(ImageSizes.CURSOROVERLAY)));
|
---|
1340 | }
|
---|
1341 | ImageIcon imageIcon = imageProvider.get();
|
---|
1342 | Image image = imageIcon.getImage();
|
---|
1343 | int width = image.getWidth(null);
|
---|
1344 | int height = image.getHeight(null);
|
---|
1345 |
|
---|
1346 | // AWT will resize the cursor to bestCursorSize internally anyway, but miss to scale the hotspot as well
|
---|
1347 | // (bug JDK-8238734). So let's do this ourselves, and also scale the hotspot accordingly.
|
---|
1348 | Dimension bestCursorSize = bestCursorSizeFunction.apply(new Dimension(width, height));
|
---|
1349 | if (bestCursorSize.width != 0 && bestCursorSize.height != 0) {
|
---|
1350 | // In principle, we could pass the MultiResolutionImage itself to AWT, but due to bug JDK-8240568,
|
---|
1351 | // this results in bad alpha blending and thus jaggy edges. So let's select the best variant ourselves.
|
---|
1352 | image = HiDPISupport.getResolutionVariant(image, bestCursorSize.width, bestCursorSize.height);
|
---|
1353 | if (bestCursorSize.width != image.getWidth(null) || bestCursorSize.height != image.getHeight(null)) {
|
---|
1354 | image = image.getScaledInstance(bestCursorSize.width, bestCursorSize.height, Image.SCALE_DEFAULT);
|
---|
1355 | }
|
---|
1356 | }
|
---|
1357 |
|
---|
1358 | hotSpot.setLocation("crosshair".equals(name) ? CROSSHAIR_HOTSPOT : DEFAULT_HOTSPOT);
|
---|
1359 | hotSpot.x = hotSpot.x * image.getWidth(null) / CURSOR_SIZE_HOTSPOT_IS_RELATIVE_TO;
|
---|
1360 | hotSpot.y = hotSpot.y * image.getHeight(null) / CURSOR_SIZE_HOTSPOT_IS_RELATIVE_TO;
|
---|
1361 |
|
---|
1362 | return image;
|
---|
1363 | }
|
---|
1364 |
|
---|
1365 | /**
|
---|
1366 | * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
|
---|
1367 | *
|
---|
1368 | * @param img the image to be scaled down.
|
---|
1369 | * @param maxSize the maximum size in pixels (both for width and height)
|
---|
1370 | *
|
---|
1371 | * @return the image after scaling.
|
---|
1372 | * @since 6172
|
---|
1373 | */
|
---|
1374 | public static Image createBoundedImage(Image img, int maxSize) {
|
---|
1375 | return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
|
---|
1376 | }
|
---|
1377 |
|
---|
1378 | /**
|
---|
1379 | * Returns a scaled instance of the provided {@code BufferedImage}.
|
---|
1380 | * This method will use a multi-step scaling technique that provides higher quality than the usual
|
---|
1381 | * one-step technique (only useful in downscaling cases, where {@code targetWidth} or {@code targetHeight} is
|
---|
1382 | * smaller than the original dimensions, and generally only when the {@code BILINEAR} hint is specified).
|
---|
1383 | * <p>
|
---|
1384 | * From <a href="https://community.oracle.com/docs/DOC-983611">"The Perils of Image.getScaledInstance()"</a>
|
---|
1385 | *
|
---|
1386 | * @param img the original image to be scaled
|
---|
1387 | * @param targetWidth the desired width of the scaled instance, in pixels
|
---|
1388 | * @param targetHeight the desired height of the scaled instance, in pixels
|
---|
1389 | * @param hint one of the rendering hints that corresponds to
|
---|
1390 | * {@code RenderingHints.KEY_INTERPOLATION} (e.g.
|
---|
1391 | * {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
|
---|
1392 | * {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
|
---|
1393 | * {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
|
---|
1394 | * @return a scaled version of the original {@code BufferedImage}
|
---|
1395 | * @since 13038
|
---|
1396 | */
|
---|
1397 | public static BufferedImage createScaledImage(BufferedImage img, int targetWidth, int targetHeight, Object hint) {
|
---|
1398 | int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
|
---|
1399 | // start with original size, then scale down in multiple passes with drawImage() until the target size is reached
|
---|
1400 | BufferedImage ret = img;
|
---|
1401 | int w = img.getWidth(null);
|
---|
1402 | int h = img.getHeight(null);
|
---|
1403 | do {
|
---|
1404 | if (w > targetWidth) {
|
---|
1405 | w /= 2;
|
---|
1406 | }
|
---|
1407 | if (w < targetWidth) {
|
---|
1408 | w = targetWidth;
|
---|
1409 | }
|
---|
1410 | if (h > targetHeight) {
|
---|
1411 | h /= 2;
|
---|
1412 | }
|
---|
1413 | if (h < targetHeight) {
|
---|
1414 | h = targetHeight;
|
---|
1415 | }
|
---|
1416 | BufferedImage tmp = new BufferedImage(w, h, type);
|
---|
1417 | Graphics2D g2 = tmp.createGraphics();
|
---|
1418 | g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
|
---|
1419 | g2.drawImage(ret, 0, 0, w, h, null);
|
---|
1420 | g2.dispose();
|
---|
1421 | ret = tmp;
|
---|
1422 | } while (w != targetWidth || h != targetHeight);
|
---|
1423 | return ret;
|
---|
1424 | }
|
---|
1425 |
|
---|
1426 | /**
|
---|
1427 | * Replies the icon for an OSM primitive type
|
---|
1428 | * @param type the type
|
---|
1429 | * @return the icon
|
---|
1430 | */
|
---|
1431 | public static ImageIcon get(OsmPrimitiveType type) {
|
---|
1432 | CheckParameterUtil.ensureParameterNotNull(type, "type");
|
---|
1433 | synchronized (osmPrimitiveTypeCache) {
|
---|
1434 | return osmPrimitiveTypeCache.computeIfAbsent(type, t -> get("data", t.getAPIName()));
|
---|
1435 | }
|
---|
1436 | }
|
---|
1437 |
|
---|
1438 | /**
|
---|
1439 | * Returns an {@link ImageIcon} for the given OSM object, at the specified size.
|
---|
1440 | * This is a slow operation.
|
---|
1441 | * @param primitive Object for which an icon shall be fetched. The icon is chosen based on tags.
|
---|
1442 | * @param iconSize Target size of icon. Icon is padded if required.
|
---|
1443 | * @return Icon for {@code primitive} that fits in cell.
|
---|
1444 | * @since 8903
|
---|
1445 | */
|
---|
1446 | public static ImageIcon getPadded(OsmPrimitive primitive, Dimension iconSize) {
|
---|
1447 | if (iconSize.width <= 0 || iconSize.height <= 0) {
|
---|
1448 | return null;
|
---|
1449 | }
|
---|
1450 | ImageResource resource = OsmPrimitiveImageProvider.getResource(primitive, OsmPrimitiveImageProvider.Options.DEFAULT);
|
---|
1451 | return resource != null ? resource.getPaddedIcon(iconSize) : null;
|
---|
1452 | }
|
---|
1453 |
|
---|
1454 | /**
|
---|
1455 | * Constructs an image from the given SVG data.
|
---|
1456 | * @param svg the SVG data
|
---|
1457 | * @param dim the desired image dimension
|
---|
1458 | * @param resizeMode how to size/resize the image
|
---|
1459 | * @return an image from the given SVG data at the desired dimension.
|
---|
1460 | */
|
---|
1461 | static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim, ImageResizeMode resizeMode) {
|
---|
1462 | if (Logging.isTraceEnabled()) {
|
---|
1463 | Logging.trace("createImageFromSvg: {0} {1}", svg.getXMLBase(), dim);
|
---|
1464 | }
|
---|
1465 | final float sourceWidth = svg.getWidth();
|
---|
1466 | final float sourceHeight = svg.getHeight();
|
---|
1467 | if (sourceWidth <= 0 || sourceHeight <= 0) {
|
---|
1468 | Logging.error("createImageFromSvg: {0} {1} sourceWidth={2} sourceHeight={3}", svg.getXMLBase(), dim, sourceWidth, sourceHeight);
|
---|
1469 | return null;
|
---|
1470 | }
|
---|
1471 | return resizeMode.createBufferedImage(dim, new Dimension((int) sourceWidth, (int) sourceHeight), g -> {
|
---|
1472 | try {
|
---|
1473 | synchronized (getSvgUniverse()) {
|
---|
1474 | svg.render(g);
|
---|
1475 | }
|
---|
1476 | } catch (SVGException ex) {
|
---|
1477 | Logging.log(Logging.LEVEL_ERROR, "Unable to load svg:", ex);
|
---|
1478 | }
|
---|
1479 | }, null);
|
---|
1480 | }
|
---|
1481 |
|
---|
1482 | private static synchronized SVGUniverse getSvgUniverse() {
|
---|
1483 | if (svgUniverse == null) {
|
---|
1484 | svgUniverse = new SVGUniverse();
|
---|
1485 | // CVE-2017-5617: Allow only data scheme (see #14319)
|
---|
1486 | svgUniverse.setImageDataInlineOnly(true);
|
---|
1487 | }
|
---|
1488 | return svgUniverse;
|
---|
1489 | }
|
---|
1490 |
|
---|
1491 | /**
|
---|
1492 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
1493 | * a supplied <code>File</code> with an <code>ImageReader</code>
|
---|
1494 | * chosen automatically from among those currently registered.
|
---|
1495 | * The <code>File</code> is wrapped in an
|
---|
1496 | * <code>ImageInputStream</code>. If no registered
|
---|
1497 | * <code>ImageReader</code> claims to be able to read the
|
---|
1498 | * resulting stream, <code>null</code> is returned.
|
---|
1499 | *
|
---|
1500 | * <p> The current cache settings from <code>getUseCache</code>and
|
---|
1501 | * <code>getCacheDirectory</code> will be used to control caching in the
|
---|
1502 | * <code>ImageInputStream</code> that is created.
|
---|
1503 | *
|
---|
1504 | * <p> Note that there is no <code>read</code> method that takes a
|
---|
1505 | * filename as a <code>String</code>; use this method instead after
|
---|
1506 | * creating a <code>File</code> from the filename.
|
---|
1507 | *
|
---|
1508 | * <p> This method does not attempt to locate
|
---|
1509 | * <code>ImageReader</code>s that can read directly from a
|
---|
1510 | * <code>File</code>; that may be accomplished using
|
---|
1511 | * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
|
---|
1512 | *
|
---|
1513 | * @param input a <code>File</code> to read from.
|
---|
1514 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color, if any.
|
---|
1515 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
1516 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
1517 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
1518 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
1519 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
1520 | *
|
---|
1521 | * @return a <code>BufferedImage</code> containing the decoded contents of the input, or <code>null</code>.
|
---|
1522 | *
|
---|
1523 | * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
|
---|
1524 | * @throws IOException if an error occurs during reading.
|
---|
1525 | * @see BufferedImage#getProperty
|
---|
1526 | * @since 7132
|
---|
1527 | */
|
---|
1528 | public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
1529 | CheckParameterUtil.ensureParameterNotNull(input, "input");
|
---|
1530 | if (!input.canRead()) {
|
---|
1531 | throw new IIOException("Can't read input file!");
|
---|
1532 | }
|
---|
1533 |
|
---|
1534 | ImageInputStream stream = createImageInputStream(input); // NOPMD
|
---|
1535 | if (stream == null) {
|
---|
1536 | throw new IIOException("Can't create an ImageInputStream!");
|
---|
1537 | }
|
---|
1538 | BufferedImage bi = read(stream, readMetadata, enforceTransparency);
|
---|
1539 | if (bi == null) {
|
---|
1540 | stream.close();
|
---|
1541 | }
|
---|
1542 | return bi;
|
---|
1543 | }
|
---|
1544 |
|
---|
1545 | /**
|
---|
1546 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
1547 | * a supplied <code>InputStream</code> with an <code>ImageReader</code>
|
---|
1548 | * chosen automatically from among those currently registered.
|
---|
1549 | * The <code>InputStream</code> is wrapped in an
|
---|
1550 | * <code>ImageInputStream</code>. If no registered
|
---|
1551 | * <code>ImageReader</code> claims to be able to read the
|
---|
1552 | * resulting stream, <code>null</code> is returned.
|
---|
1553 | *
|
---|
1554 | * <p> The current cache settings from <code>getUseCache</code>and
|
---|
1555 | * <code>getCacheDirectory</code> will be used to control caching in the
|
---|
1556 | * <code>ImageInputStream</code> that is created.
|
---|
1557 | *
|
---|
1558 | * <p> This method does not attempt to locate
|
---|
1559 | * <code>ImageReader</code>s that can read directly from an
|
---|
1560 | * <code>InputStream</code>; that may be accomplished using
|
---|
1561 | * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
|
---|
1562 | *
|
---|
1563 | * <p> This method <em>does not</em> close the provided
|
---|
1564 | * <code>InputStream</code> after the read operation has completed;
|
---|
1565 | * it is the responsibility of the caller to close the stream, if desired.
|
---|
1566 | *
|
---|
1567 | * @param input an <code>InputStream</code> to read from.
|
---|
1568 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
|
---|
1569 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
1570 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
1571 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
1572 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
1573 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
1574 | *
|
---|
1575 | * @return a <code>BufferedImage</code> containing the decoded contents of the input, or <code>null</code>.
|
---|
1576 | *
|
---|
1577 | * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
|
---|
1578 | * @throws IOException if an error occurs during reading.
|
---|
1579 | * @since 7132
|
---|
1580 | */
|
---|
1581 | public static BufferedImage read(InputStream input, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
1582 | CheckParameterUtil.ensureParameterNotNull(input, "input");
|
---|
1583 |
|
---|
1584 | ImageInputStream stream = createImageInputStream(input); // NOPMD
|
---|
1585 | BufferedImage bi = read(stream, readMetadata, enforceTransparency);
|
---|
1586 | if (bi == null) {
|
---|
1587 | stream.close();
|
---|
1588 | }
|
---|
1589 | return bi;
|
---|
1590 | }
|
---|
1591 |
|
---|
1592 | /**
|
---|
1593 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
1594 | * a supplied <code>URL</code> with an <code>ImageReader</code>
|
---|
1595 | * chosen automatically from among those currently registered. An
|
---|
1596 | * <code>InputStream</code> is obtained from the <code>URL</code>,
|
---|
1597 | * which is wrapped in an <code>ImageInputStream</code>. If no
|
---|
1598 | * registered <code>ImageReader</code> claims to be able to read
|
---|
1599 | * the resulting stream, <code>null</code> is returned.
|
---|
1600 | *
|
---|
1601 | * <p> The current cache settings from <code>getUseCache</code>and
|
---|
1602 | * <code>getCacheDirectory</code> will be used to control caching in the
|
---|
1603 | * <code>ImageInputStream</code> that is created.
|
---|
1604 | *
|
---|
1605 | * <p> This method does not attempt to locate
|
---|
1606 | * <code>ImageReader</code>s that can read directly from a
|
---|
1607 | * <code>URL</code>; that may be accomplished using
|
---|
1608 | * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
|
---|
1609 | *
|
---|
1610 | * @param input a <code>URL</code> to read from.
|
---|
1611 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
|
---|
1612 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
1613 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
1614 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
1615 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
1616 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
1617 | *
|
---|
1618 | * @return a <code>BufferedImage</code> containing the decoded contents of the input, or <code>null</code>.
|
---|
1619 | *
|
---|
1620 | * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
|
---|
1621 | * @throws IOException if an error occurs during reading.
|
---|
1622 | * @since 7132
|
---|
1623 | */
|
---|
1624 | public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
1625 | return read(input, readMetadata, enforceTransparency, ImageReader::getDefaultReadParam);
|
---|
1626 | }
|
---|
1627 |
|
---|
1628 | /**
|
---|
1629 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
1630 | * a supplied <code>URL</code> with an <code>ImageReader</code>
|
---|
1631 | * chosen automatically from among those currently registered. An
|
---|
1632 | * <code>InputStream</code> is obtained from the <code>URL</code>,
|
---|
1633 | * which is wrapped in an <code>ImageInputStream</code>. If no
|
---|
1634 | * registered <code>ImageReader</code> claims to be able to read
|
---|
1635 | * the resulting stream, <code>null</code> is returned.
|
---|
1636 | *
|
---|
1637 | * <p> The current cache settings from <code>getUseCache</code>and
|
---|
1638 | * <code>getCacheDirectory</code> will be used to control caching in the
|
---|
1639 | * <code>ImageInputStream</code> that is created.
|
---|
1640 | *
|
---|
1641 | * <p> This method does not attempt to locate
|
---|
1642 | * <code>ImageReader</code>s that can read directly from a
|
---|
1643 | * <code>URL</code>; that may be accomplished using
|
---|
1644 | * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
|
---|
1645 | *
|
---|
1646 | * @param input a <code>URL</code> to read from.
|
---|
1647 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
|
---|
1648 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
1649 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
1650 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
1651 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
1652 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
1653 | * @param readParamFunction a function to compute the read parameters from the image reader
|
---|
1654 | *
|
---|
1655 | * @return a <code>BufferedImage</code> containing the decoded contents of the input, or <code>null</code>.
|
---|
1656 | *
|
---|
1657 | * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
|
---|
1658 | * @throws IOException if an error occurs during reading.
|
---|
1659 | * @since 17880
|
---|
1660 | */
|
---|
1661 | public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency,
|
---|
1662 | Function<ImageReader, ImageReadParam> readParamFunction) throws IOException {
|
---|
1663 | CheckParameterUtil.ensureParameterNotNull(input, "input");
|
---|
1664 |
|
---|
1665 | try (InputStream istream = Utils.openStream(input)) {
|
---|
1666 | ImageInputStream stream = createImageInputStream(istream); // NOPMD
|
---|
1667 | BufferedImage bi = read(stream, readMetadata, enforceTransparency, readParamFunction);
|
---|
1668 | if (bi == null) {
|
---|
1669 | stream.close();
|
---|
1670 | }
|
---|
1671 | return bi;
|
---|
1672 | } catch (SecurityException e) {
|
---|
1673 | throw new IOException(e);
|
---|
1674 | }
|
---|
1675 | }
|
---|
1676 |
|
---|
1677 | /**
|
---|
1678 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
1679 | * a supplied <code>ImageInputStream</code> with an
|
---|
1680 | * <code>ImageReader</code> chosen automatically from among those
|
---|
1681 | * currently registered. If no registered
|
---|
1682 | * <code>ImageReader</code> claims to be able to read the stream,
|
---|
1683 | * <code>null</code> is returned.
|
---|
1684 | *
|
---|
1685 | * <p> Unlike most other methods in this class, this method <em>does</em>
|
---|
1686 | * close the provided <code>ImageInputStream</code> after the read
|
---|
1687 | * operation has completed, unless <code>null</code> is returned,
|
---|
1688 | * in which case this method <em>does not</em> close the stream.
|
---|
1689 | *
|
---|
1690 | * @param stream an <code>ImageInputStream</code> to read from.
|
---|
1691 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
|
---|
1692 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
1693 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
1694 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
1695 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
1696 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color. For Java < 11 only.
|
---|
1697 | *
|
---|
1698 | * @return a <code>BufferedImage</code> containing the decoded
|
---|
1699 | * contents of the input, or <code>null</code>.
|
---|
1700 | *
|
---|
1701 | * @throws IllegalArgumentException if <code>stream</code> is <code>null</code>.
|
---|
1702 | * @throws IOException if an error occurs during reading.
|
---|
1703 | * @since 7132
|
---|
1704 | */
|
---|
1705 | public static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
1706 | return read(stream, readMetadata, enforceTransparency, ImageReader::getDefaultReadParam);
|
---|
1707 | }
|
---|
1708 |
|
---|
1709 | private static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency,
|
---|
1710 | Function<ImageReader, ImageReadParam> readParamFunction) throws IOException {
|
---|
1711 | CheckParameterUtil.ensureParameterNotNull(stream, "stream");
|
---|
1712 |
|
---|
1713 | Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
|
---|
1714 | if (!iter.hasNext()) {
|
---|
1715 | return null;
|
---|
1716 | }
|
---|
1717 |
|
---|
1718 | ImageReader reader = iter.next();
|
---|
1719 | reader.setInput(stream, true, !readMetadata && !enforceTransparency);
|
---|
1720 | ImageReadParam param = readParamFunction.apply(reader);
|
---|
1721 | BufferedImage bi = null;
|
---|
1722 | try (stream) {
|
---|
1723 | bi = reader.read(0, param);
|
---|
1724 | } catch (LinkageError e) {
|
---|
1725 | // On Windows, ComponentColorModel.getRGBComponent can fail with "UnsatisfiedLinkError: no awt in java.library.path", see #13973
|
---|
1726 | // Then it can leads to "NoClassDefFoundError: Could not initialize class sun.awt.image.ShortInterleavedRaster", see #15079
|
---|
1727 | Logging.error(e);
|
---|
1728 | } finally {
|
---|
1729 | reader.dispose();
|
---|
1730 | }
|
---|
1731 | return bi;
|
---|
1732 | }
|
---|
1733 |
|
---|
1734 | // CHECKSTYLE.OFF: LineLength
|
---|
1735 |
|
---|
1736 | /**
|
---|
1737 | * Returns the {@code TransparentColor} defined in image reader metadata.
|
---|
1738 | * @param model The image color model
|
---|
1739 | * @param reader The image reader
|
---|
1740 | * @return the {@code TransparentColor} defined in image reader metadata, or {@code null}
|
---|
1741 | * @throws IOException if an error occurs during reading
|
---|
1742 | * @see <a href="https://docs.oracle.com/javase/8/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html">javax_imageio_1.0 metadata</a>
|
---|
1743 | * @since 7499
|
---|
1744 | */
|
---|
1745 | public static Color getTransparentColor(ColorModel model, ImageReader reader) throws IOException {
|
---|
1746 | // CHECKSTYLE.ON: LineLength
|
---|
1747 | try {
|
---|
1748 | IIOMetadata metadata = reader.getImageMetadata(0);
|
---|
1749 | if (metadata != null) {
|
---|
1750 | String[] formats = metadata.getMetadataFormatNames();
|
---|
1751 | if (formats != null) {
|
---|
1752 | for (String f : formats) {
|
---|
1753 | if ("javax_imageio_1.0".equals(f)) {
|
---|
1754 | Node root = metadata.getAsTree(f);
|
---|
1755 | if (root instanceof Element) {
|
---|
1756 | NodeList list = ((Element) root).getElementsByTagName("TransparentColor");
|
---|
1757 | if (list.getLength() > 0) {
|
---|
1758 | Node item = list.item(0);
|
---|
1759 | if (item instanceof Element) {
|
---|
1760 | // Handle different color spaces (tested with RGB and grayscale)
|
---|
1761 | String value = ((Element) item).getAttribute("value");
|
---|
1762 | if (!value.isEmpty()) {
|
---|
1763 | String[] s = value.split(" ", -1);
|
---|
1764 | if (s.length == 3) {
|
---|
1765 | return parseRGB(s);
|
---|
1766 | } else if (s.length == 1) {
|
---|
1767 | int pixel = Integer.parseInt(s[0]);
|
---|
1768 | int r = model.getRed(pixel);
|
---|
1769 | int g = model.getGreen(pixel);
|
---|
1770 | int b = model.getBlue(pixel);
|
---|
1771 | return new Color(r, g, b);
|
---|
1772 | } else {
|
---|
1773 | Logging.warn("Unable to translate TransparentColor '"+value+"' with color model "+model);
|
---|
1774 | }
|
---|
1775 | }
|
---|
1776 | }
|
---|
1777 | }
|
---|
1778 | }
|
---|
1779 | break;
|
---|
1780 | }
|
---|
1781 | }
|
---|
1782 | }
|
---|
1783 | }
|
---|
1784 | } catch (IIOException | NumberFormatException e) {
|
---|
1785 | // JAI doesn't like some JPEG files with error "Inconsistent metadata read from stream" (see #10267)
|
---|
1786 | Logging.warn(e);
|
---|
1787 | }
|
---|
1788 | return null;
|
---|
1789 | }
|
---|
1790 |
|
---|
1791 | private static Color parseRGB(String... s) {
|
---|
1792 | try {
|
---|
1793 | int[] rgb = IntStream.range(0, 3).map(i -> Integer.parseInt(s[i])).toArray();
|
---|
1794 | return new Color(rgb[0], rgb[1], rgb[2]);
|
---|
1795 | } catch (IllegalArgumentException e) {
|
---|
1796 | Logging.error(e);
|
---|
1797 | return null;
|
---|
1798 | }
|
---|
1799 | }
|
---|
1800 |
|
---|
1801 | /**
|
---|
1802 | * Returns a transparent version of the given image, based on the given transparent color.
|
---|
1803 | * @param bi The image to convert
|
---|
1804 | * @param color The transparent color
|
---|
1805 | * @return The same image as {@code bi} where all pixels of the given color are transparent.
|
---|
1806 | * This resulting image has also the special property {@link #PROP_TRANSPARENCY_FORCED} set to {@code color}
|
---|
1807 | * @see BufferedImage#getProperty
|
---|
1808 | * @see #isTransparencyForced
|
---|
1809 | * @since 7132
|
---|
1810 | */
|
---|
1811 | public static BufferedImage makeImageTransparent(BufferedImage bi, Color color) {
|
---|
1812 | // the color we are looking for. Alpha bits are set to opaque
|
---|
1813 | final int markerRGB = color.getRGB() | 0xFF000000;
|
---|
1814 | ImageFilter filter = new RGBImageFilter() {
|
---|
1815 | @Override
|
---|
1816 | public int filterRGB(int x, int y, int rgb) {
|
---|
1817 | if ((rgb | 0xFF000000) == markerRGB) {
|
---|
1818 | // Mark the alpha bits as zero - transparent
|
---|
1819 | return 0x00FFFFFF & rgb;
|
---|
1820 | } else {
|
---|
1821 | return rgb;
|
---|
1822 | }
|
---|
1823 | }
|
---|
1824 | };
|
---|
1825 | ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
|
---|
1826 | Image img = Toolkit.getDefaultToolkit().createImage(ip);
|
---|
1827 | ColorModel colorModel = ColorModel.getRGBdefault();
|
---|
1828 | WritableRaster raster = colorModel.createCompatibleWritableRaster(img.getWidth(null), img.getHeight(null));
|
---|
1829 | String[] names = bi.getPropertyNames();
|
---|
1830 | Hashtable<String, Object> properties = new Hashtable<>(1 + (names != null ? names.length : 0));
|
---|
1831 | if (names != null) {
|
---|
1832 | for (String name : names) {
|
---|
1833 | properties.put(name, bi.getProperty(name));
|
---|
1834 | }
|
---|
1835 | }
|
---|
1836 | properties.put(PROP_TRANSPARENCY_FORCED, Boolean.TRUE);
|
---|
1837 | BufferedImage result = new BufferedImage(colorModel, raster, false, properties);
|
---|
1838 | Graphics2D g2 = result.createGraphics();
|
---|
1839 | g2.drawImage(img, 0, 0, null);
|
---|
1840 | g2.dispose();
|
---|
1841 | return result;
|
---|
1842 | }
|
---|
1843 |
|
---|
1844 | /**
|
---|
1845 | * Determines if the transparency of the given {@code BufferedImage} has been enforced by a previous call to {@link #makeImageTransparent}.
|
---|
1846 | * @param bi The {@code BufferedImage} to test
|
---|
1847 | * @return {@code true} if the transparency of {@code bi} has been enforced by a previous call to {@code makeImageTransparent}.
|
---|
1848 | * @see #makeImageTransparent
|
---|
1849 | * @since 7132
|
---|
1850 | */
|
---|
1851 | public static boolean isTransparencyForced(BufferedImage bi) {
|
---|
1852 | return bi != null && !bi.getProperty(PROP_TRANSPARENCY_FORCED).equals(Image.UndefinedProperty);
|
---|
1853 | }
|
---|
1854 |
|
---|
1855 | /**
|
---|
1856 | * Determines if the given {@code BufferedImage} has a transparent color determined by a previous call to {@link #read}.
|
---|
1857 | * @param bi The {@code BufferedImage} to test
|
---|
1858 | * @return {@code true} if {@code bi} has a transparent color determined by a previous call to {@code read}.
|
---|
1859 | * @see #read
|
---|
1860 | * @since 7132
|
---|
1861 | */
|
---|
1862 | public static boolean hasTransparentColor(BufferedImage bi) {
|
---|
1863 | return bi != null && !bi.getProperty(PROP_TRANSPARENCY_COLOR).equals(Image.UndefinedProperty);
|
---|
1864 | }
|
---|
1865 |
|
---|
1866 | /**
|
---|
1867 | * Shutdown background image fetcher.
|
---|
1868 | * @param now if {@code true}, attempts to stop all actively executing tasks, halts the processing of waiting tasks.
|
---|
1869 | * if {@code false}, initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted
|
---|
1870 | * @since 8412
|
---|
1871 | */
|
---|
1872 | public static void shutdown(boolean now) {
|
---|
1873 | try {
|
---|
1874 | if (now) {
|
---|
1875 | IMAGE_FETCHER.shutdownNow();
|
---|
1876 | } else {
|
---|
1877 | IMAGE_FETCHER.shutdown();
|
---|
1878 | }
|
---|
1879 | } catch (SecurityException ex) {
|
---|
1880 | Logging.log(Logging.LEVEL_ERROR, "Failed to shutdown background image fetcher.", ex);
|
---|
1881 | }
|
---|
1882 | }
|
---|
1883 |
|
---|
1884 | /**
|
---|
1885 | * Converts an {@link Image} to a {@link BufferedImage} instance.
|
---|
1886 | * @param image image to convert
|
---|
1887 | * @return a {@code BufferedImage} instance for the given {@code Image}.
|
---|
1888 | * @since 13038
|
---|
1889 | */
|
---|
1890 | public static BufferedImage toBufferedImage(Image image) {
|
---|
1891 | if (image instanceof BufferedImage) {
|
---|
1892 | return (BufferedImage) image;
|
---|
1893 | } else {
|
---|
1894 | BufferedImage buffImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
|
---|
1895 | Graphics2D g2 = buffImage.createGraphics();
|
---|
1896 | g2.drawImage(image, 0, 0, null);
|
---|
1897 | g2.dispose();
|
---|
1898 | return buffImage;
|
---|
1899 | }
|
---|
1900 | }
|
---|
1901 |
|
---|
1902 | /**
|
---|
1903 | * Converts an {@link Rectangle} area of {@link Image} to a {@link BufferedImage} instance.
|
---|
1904 | * @param image image to convert
|
---|
1905 | * @param cropArea rectangle to crop image with
|
---|
1906 | * @return a {@code BufferedImage} instance for the cropped area of {@code Image}.
|
---|
1907 | * @since 13127
|
---|
1908 | */
|
---|
1909 | public static BufferedImage toBufferedImage(Image image, Rectangle cropArea) {
|
---|
1910 | BufferedImage buffImage = null;
|
---|
1911 | Rectangle r = new Rectangle(image.getWidth(null), image.getHeight(null));
|
---|
1912 | if (r.intersection(cropArea).equals(cropArea)) {
|
---|
1913 | buffImage = new BufferedImage(cropArea.width, cropArea.height, BufferedImage.TYPE_INT_ARGB);
|
---|
1914 | Graphics2D g2 = buffImage.createGraphics();
|
---|
1915 | g2.drawImage(image, 0, 0, cropArea.width, cropArea.height,
|
---|
1916 | cropArea.x, cropArea.y, cropArea.x + cropArea.width, cropArea.y + cropArea.height, null);
|
---|
1917 | g2.dispose();
|
---|
1918 | }
|
---|
1919 | return buffImage;
|
---|
1920 | }
|
---|
1921 |
|
---|
1922 | private static ImageInputStream createImageInputStream(Object input) throws IOException {
|
---|
1923 | try {
|
---|
1924 | return ImageIO.createImageInputStream(input);
|
---|
1925 | } catch (SecurityException e) {
|
---|
1926 | if (ImageIO.getUseCache()) {
|
---|
1927 | ImageIO.setUseCache(false);
|
---|
1928 | return ImageIO.createImageInputStream(input);
|
---|
1929 | }
|
---|
1930 | throw new IOException(e);
|
---|
1931 | }
|
---|
1932 | }
|
---|
1933 |
|
---|
1934 | /**
|
---|
1935 | * Creates a blank icon of the given size.
|
---|
1936 | * @param size image size
|
---|
1937 | * @return a blank icon of the given size
|
---|
1938 | * @since 13984
|
---|
1939 | */
|
---|
1940 | public static ImageIcon createBlankIcon(ImageSizes size) {
|
---|
1941 | return new ImageIcon(new BufferedImage(size.getAdjustedWidth(), size.getAdjustedHeight(), BufferedImage.TYPE_INT_ARGB));
|
---|
1942 | }
|
---|
1943 |
|
---|
1944 | @Override
|
---|
1945 | public String toString() {
|
---|
1946 | return ("ImageProvider ["
|
---|
1947 | + (!Utils.isEmpty(dirs) ? "dirs=" + dirs + ", " : "") + (id != null ? "id=" + id + ", " : "")
|
---|
1948 | + (!Utils.isEmpty(subdir) ? "subdir=" + subdir + ", " : "") + "name=" + name + ", "
|
---|
1949 | + (archive != null ? "archive=" + archive + ", " : "")
|
---|
1950 | + (!Utils.isEmpty(inArchiveDir) ? "inArchiveDir=" + inArchiveDir : "") + ']').replaceAll(", \\]", "]");
|
---|
1951 | }
|
---|
1952 | }
|
---|