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

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

fix #19706, fix #19725 - ImageProvider/ImageResource: extract ImageResizeMode, add HiDPI support to bounded/padded icons

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