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

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

fix #16797 - NPE

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