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