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

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

fix #19751 - MapImage.rescale: use original SVG instead of rastered version

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