source: josm/trunk/src/org/openstreetmap/josm/tools/ImageProvider.java@ 16792

Last change on this file since 16792 was 16792, checked in by simon04, 4 years ago

fix #19496 - ImageProvider.getPadded: deprioritize multipolygon icon

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