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

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

see #20141 - ImageProvider: cache rendered SVG images using JCS

This experimental feature is disabled by default. Set the advanced preference jcs.cache.use_image_resource_cache=true to enable. No cache eviction for altered images is implemented at the moment.

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