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

Last change on this file since 14284 was 14284, checked in by Don-vip, 6 years ago

fix #16778 - cache padded icons to improve performance when filtering relations

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