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

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

fix #15662 - allow JOSM to open JAR URLs containing exclamation marks (workaround to https://bugs.openjdk.java.net/browse/JDK-4523159)

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