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

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

sonarqube - squid:S4551 - Enum values should be compared with "=="

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