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

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

see #14088 - Fix SelectionTableCellRendererTest, MemberTableMemberCellRendererTest

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