Class ImageProvider

java.lang.Object
org.openstreetmap.josm.tools.ImageProvider

public class ImageProvider extends Object
Helper class to support the application with images.

How to use:

ImageIcon icon = new ImageProvider(name).setMaxSize(ImageSizes.MAP).get(); (there are more options, see below)

short form: ImageIcon icon = ImageProvider.get(name);

  • Field Details

  • Constructor Details

    • ImageProvider

      public ImageProvider(String subdir, String name)
      Constructs a new ImageProvider from a filename in a given directory.
      Parameters:
      subdir - subdirectory the image lies in
      name - the name of the image. If it does not end with '.png' or '.svg', both extensions are tried.
      Throws:
      NullPointerException - if name is null
    • ImageProvider

      public ImageProvider(String name)
      Constructs a new ImageProvider from a filename.
      Parameters:
      name - the name of the image. If it does not end with '.png' or '.svg', both extensions are tried.
      Throws:
      NullPointerException - if name is null
    • ImageProvider

      Constructs a new ImageProvider from an existing one.
      Parameters:
      image - the existing image provider to be copied
      Since:
      8095
  • Method Details

    • setDirs

      Directories to look for the image.
      Parameters:
      dirs - The directories to look for.
      Returns:
      the current object, for convenience
    • setId

      public ImageProvider setId(String id)
      Set an id used for caching. If name starts with http:// Id is not used for the cache. (A URL is unique anyway.)
      Parameters:
      id - the id for the cached image
      Returns:
      the current object, for convenience
    • setArchive

      public ImageProvider setArchive(File archive)
      Specify a zip file where the image is located.

      (optional)

      Parameters:
      archive - zip file where the image is located
      Returns:
      the current object, for convenience
    • setInArchiveDir

      public ImageProvider setInArchiveDir(String inArchiveDir)
      Specify a base path inside the zip file.

      The subdir and name will be relative to this path.

      (optional)

      Parameters:
      inArchiveDir - path inside the archive
      Returns:
      the current object, for convenience
    • addOverlay

      Add an overlay over the image. Multiple overlays are possible.
      Parameters:
      overlay - overlay image and placement specification
      Returns:
      the current object, for convenience
      Since:
      8095
    • setSize

      Set the dimensions of the image.

      If not specified, the original size of the image is used. The width part of the dimension can be -1. Then it will only set the height but keep the aspect ratio. (And the other way around.)

      Parameters:
      size - final dimensions of the image
      Returns:
      the current object, for convenience
    • setSize

      Set the dimensions of the image.

      If not specified, the original size of the image is used.

      Parameters:
      size - final dimensions of the image
      Returns:
      the current object, for convenience
      Since:
      7687
    • setSize

      public ImageProvider setSize(int width, int height)
      Set the dimensions of the image.
      Parameters:
      width - final width of the image
      height - final height of the image
      Returns:
      the current object, for convenience
      Since:
      10358
    • setWidth

      public ImageProvider setWidth(int width)
      Set image width
      Parameters:
      width - final width of the image
      Returns:
      the current object, for convenience
      See Also:
    • setHeight

      public ImageProvider setHeight(int height)
      Set image height
      Parameters:
      height - final height of the image
      Returns:
      the current object, for convenience
      See Also:
    • setMaxSize

      Limit the maximum size of the image.

      It will shrink the image if necessary, but keep the aspect ratio. The given width or height can be -1 which means this direction is not bounded.

      'size' and 'maxSize' are not compatible, you should set only one of them.

      Parameters:
      maxSize - maximum image size
      Returns:
      the current object, for convenience
    • resetMaxSize

      Limit the maximum size of the image.

      It will shrink the image if necessary, but keep the aspect ratio. The given width or height can be -1 which means this direction is not bounded.

      This function sets value using the most restrictive of the new or existing set of values.

      Parameters:
      maxSize - maximum image size
      Returns:
      the current object, for convenience
      See Also:
    • setMaxSize

      Limit the maximum size of the image.

      It will shrink the image if necessary, but keep the aspect ratio. The given width or height can be -1 which means this direction is not bounded.

      'size' and 'maxSize' are not compatible, you should set only one of them.

      Parameters:
      size - maximum image size
      Returns:
      the current object, for convenience
      Since:
      7687
    • setMaxSize

      public ImageProvider setMaxSize(int maxSize)
      Convenience method, see setMaxSize(Dimension).
      Parameters:
      maxSize - maximum image size
      Returns:
      the current object, for convenience
    • setMaxWidth

      public ImageProvider setMaxWidth(int maxWidth)
      Limit the maximum width of the image.
      Parameters:
      maxWidth - maximum image width
      Returns:
      the current object, for convenience
      See Also:
    • setMaxHeight

      public ImageProvider setMaxHeight(int maxHeight)
      Limit the maximum height of the image.
      Parameters:
      maxHeight - maximum image height
      Returns:
      the current object, for convenience
      See Also:
    • setOptional

      public ImageProvider setOptional(boolean optional)
      Decide, if an exception should be thrown, when the image cannot be located.

      Set to true, when the image URL comes from user data and the image may be missing.

      Parameters:
      optional - true, if JOSM should not throw a RuntimeException in case the image cannot be located.
      Returns:
      the current object, for convenience
    • setSuppressWarnings

      public ImageProvider setSuppressWarnings(boolean suppressWarnings)
      Suppresses warning on the command line in case the image cannot be found.

      In combination with setOptional(true);

      Parameters:
      suppressWarnings - if true warnings are suppressed
      Returns:
      the current object, for convenience
    • setDisabled

      public ImageProvider setDisabled(boolean disabled)
      Set, if image must be filtered to grayscale so it will look like disabled icon.
      Parameters:
      disabled - true, if image must be grayed out for disabled state
      Returns:
      the current object, for convenience
      Since:
      10428
    • setMultiResolution

      public ImageProvider setMultiResolution(boolean multiResolution)
      Decide, if multi-resolution image is requested (default true).

      A java.awt.image.MultiResolutionImage is a Java 9 Image implementation, which adds support for HiDPI displays. The effect will be that in HiDPI mode, when GUI elements are scaled by a factor 1.5, 2.0, etc., the images are not just up-scaled, but a higher resolution version of the image is rendered instead.

      Use HiDPISupport.getBaseImage(java.awt.Image) to extract the original image from a multi-resolution image.

      See HiDPISupport.processMRImage(java.awt.Image, java.util.function.UnaryOperator<java.awt.Image>) for how to process the image without removing the multi-resolution magic.

      Parameters:
      multiResolution - true, if multi-resolution image is requested
      Returns:
      the current object, for convenience
    • isRemote

      public boolean isRemote()
      Determines if this icon is located on a remote location (http, https, wiki).
      Returns:
      true if this icon is located on a remote location (http, https, wiki)
      Since:
      13250
    • get

      public ImageIcon get()
      Execute the image request and scale result.
      Returns:
      the requested image or null if the request failed
    • getDataURL

      public String getDataURL()
      Execute the image request and scale result.
      Returns:
      the requested image as data: URL or null if the request failed
      Since:
      16872
    • getAsync

      public CompletableFuture<Void> getAsync(Consumer<? super ImageIcon> action)
      Load the image in a background thread.

      This method returns immediately and runs the image request asynchronously.

      Parameters:
      action - the action that will deal with the image
      Returns:
      the future of the requested image
      Since:
      13252
    • getResource

      Execute the image request.
      Returns:
      the requested image or null if the request failed
      Since:
      7693
    • getResourceAsync

      Load the image in a background thread.

      This method returns immediately and runs the image request asynchronously for remote resources. For local resources, the request is executed synchronously in the current thread.

      Parameters:
      action - the action that will deal with the image
      Returns:
      the future of the requested image
      Since:
      13252
    • getImageFetchExecutor

      Returns the executor used for background image fetching. Callers that need to force asynchronous loading even for local resources (e.g. to off-load expensive SVG pre-rendering) may use this executor directly.
      Returns:
      the image fetch executor
      Since:
      19553
    • get

      public static ImageIcon get(String subdir, String name)
      Load an image with a given file name.
      Parameters:
      subdir - subdirectory the image lies in
      name - The icon name (base name with or without '.png' or '.svg' extension)
      Returns:
      The requested Image.
      Throws:
      RuntimeException - if the image cannot be located
    • get

      public static ImageIcon get(String name)
      Load an image with a given file name.
      Parameters:
      name - The icon name (base name with or without '.png' or '.svg' extension)
      Returns:
      the requested image or null if the request failed
      See Also:
    • get

      public static ImageIcon get(String subdir, String name, ImageProvider.ImageSizes size)
      Load an image from directory with a given file name and size.
      Parameters:
      subdir - subdirectory the image lies in
      name - The icon name (base name with or without '.png' or '.svg' extension)
      size - Target icon size
      Returns:
      The requested Image.
      Throws:
      RuntimeException - if the image cannot be located
      Since:
      10428
    • getEmpty

      Load an empty image with a given size.
      Parameters:
      size - Target icon size
      Returns:
      The requested Image.
      Since:
      10358
    • getIfAvailable

      public static ImageIcon getIfAvailable(String subdir, String name)
      Load an image with a given file name, but do not throw an exception when the image cannot be found.
      Parameters:
      subdir - subdirectory the image lies in
      name - The icon name (base name with or without '.png' or '.svg' extension)
      Returns:
      the requested image or null if the request failed
      See Also:
    • get

      public static ImageIcon get(String name, ImageProvider.ImageSizes size)
      Load an image with a given file name and size.
      Parameters:
      name - The icon name (base name with or without '.png' or '.svg' extension)
      size - Target icon size
      Returns:
      the requested image or null if the request failed
      Since:
      10428
      See Also:
    • getIfAvailable

      public static ImageIcon getIfAvailable(String name)
      Load an image with a given file name, but do not throw an exception when the image cannot be found.
      Parameters:
      name - The icon name (base name with or without '.png' or '.svg' extension)
      Returns:
      the requested image or null if the request failed
      See Also:
    • clearCache

      public static void clearCache()
      Clears the internal image caches.
      Since:
      11021
    • getIfAvailableImpl

      Internal implementation of the image request.
      Returns:
      the requested image or null if the request failed
    • getIfAvailableHttp

      Internal implementation of the image request for URL's.
      Parameters:
      url - URL of the image
      type - data type of the image
      Returns:
      the requested image or null if the request failed
    • getIfAvailableDataUrl

      Internal implementation of the image request for inline images (data: urls).
      Parameters:
      url - the data URL for image extraction
      Returns:
      the requested image or null if the request failed
    • getIfAvailableWiki

      Internal implementation of the image request for wiki images.
      Parameters:
      name - image file name
      type - data type of the image
      Returns:
      the requested image or null if the request failed
    • getIfAvailableZip

      private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageProvider.ImageType type)
      Internal implementation of the image request for images in Zip archives.
      Parameters:
      fullName - image file name
      archive - the archive to get image from
      inArchiveDir - directory of the image inside the archive or null
      type - data type of the image
      Returns:
      the requested image or null if the request failed
    • getIfAvailableLocalURL

      Internal implementation of the image request for local images.
      Parameters:
      path - image file path
      type - data type of the image
      Returns:
      the requested image or null if the request failed
    • getImageUrl

      private static URL getImageUrl(String path, String name)
    • getImageUrl

      private URL getImageUrl(String imageName)
    • getImgUrlFromWikiInfoPage

      private static String getImgUrlFromWikiInfoPage(String base, String fn)
      Reads the wiki page on a certain file in html format in order to find the real image URL.
      Parameters:
      base - base URL for Wiki image
      fn - filename of the Wiki image
      Returns:
      image URL for a Wiki image or null in case of error
    • getCursor

      public static Cursor getCursor(String name, String overlay)
      Load a cursor with a given file name, optionally decorated with an overlay image.
      Parameters:
      name - the cursor image filename in "cursor" directory
      overlay - optional overlay image
      Returns:
      cursor with a given file name, optionally decorated with an overlay image
    • getCursorImage

      static Image getCursorImage(String name, String overlay, UnaryOperator<Dimension> bestCursorSizeFunction, Point hotSpot)
      Load a cursor image with a given file name, optionally decorated with an overlay image
      Parameters:
      name - the cursor image filename in "cursor" directory
      overlay - optional overlay image
      bestCursorSizeFunction - computes the best cursor size, see Toolkit.getBestCursorSize(int, int)
      hotSpot - will be set to the properly scaled hotspot of the cursor
      Returns:
      cursor with a given file name, optionally decorated with an overlay image
    • createBoundedImage

      public static Image createBoundedImage(Image img, int maxSize)
      Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
      Parameters:
      img - the image to be scaled down.
      maxSize - the maximum size in pixels (both for width and height)
      Returns:
      the image after scaling.
      Since:
      6172
    • createScaledImage

      public static BufferedImage createScaledImage(BufferedImage img, int targetWidth, int targetHeight, Object hint)
      Returns a scaled instance of the provided BufferedImage. This method will use a multi-step scaling technique that provides higher quality than the usual one-step technique (only useful in downscaling cases, where targetWidth or targetHeight is smaller than the original dimensions, and generally only when the BILINEAR hint is specified).

      From "The Perils of Image.getScaledInstance()"

      Parameters:
      img - the original image to be scaled
      targetWidth - the desired width of the scaled instance, in pixels
      targetHeight - the desired height of the scaled instance, in pixels
      hint - one of the rendering hints that corresponds to RenderingHints.KEY_INTERPOLATION (e.g. RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RenderingHints.VALUE_INTERPOLATION_BICUBIC)
      Returns:
      a scaled version of the original BufferedImage
      Since:
      13038
    • get

      public static ImageIcon get(OsmPrimitiveType type)
      Replies the icon for an OSM primitive type
      Parameters:
      type - the type
      Returns:
      the icon
    • getPadded

      public static ImageIcon getPadded(OsmPrimitive primitive, Dimension iconSize)
      Returns an ImageIcon for the given OSM object, at the specified size. This is a slow operation.
      Parameters:
      primitive - Object for which an icon shall be fetched. The icon is chosen based on tags.
      iconSize - Target size of icon. Icon is padded if required.
      Returns:
      Icon for primitive that fits in cell.
      Since:
      8903
    • createImageFromSvg

      static BufferedImage createImageFromSvg(com.github.weisj.jsvg.SVGDocument svg, Dimension dim, ImageResizeMode resizeMode)
      Constructs an image from the given SVG data.
      Parameters:
      svg - the SVG data
      dim - the desired image dimension
      resizeMode - how to size/resize the image
      Returns:
      an image from the given SVG data at the desired dimension.
    • read

      public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException
      Returns a BufferedImage as the result of decoding a supplied File with an ImageReader chosen automatically from among those currently registered. The File is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

      The current cache settings from getUseCacheand getCacheDirectory will be used to control caching in the ImageInputStream that is created.

      Note that there is no read method that takes a filename as a String; use this method instead after creating a File from the filename.

      This method does not attempt to locate ImageReaders that can read directly from a File; that may be accomplished using IIORegistry and ImageReaderSpi.

      Parameters:
      input - a File to read from.
      readMetadata - if true, makes sure to read image metadata to detect transparency color, if any. In that case the color can be retrieved later through PROP_TRANSPARENCY_COLOR. Always considered true if enforceTransparency is also true
      enforceTransparency - if true, makes sure to read image metadata and, if the image does not provide an alpha channel but defines a TransparentColor metadata node, that the resulting image has a transparency set to TRANSLUCENT and uses the correct transparent color.
      Returns:
      a BufferedImage containing the decoded contents of the input, or null.
      Throws:
      IllegalArgumentException - if input is null.
      IOException - if an error occurs during reading.
      Since:
      7132
      See Also:
    • read

      public static BufferedImage read(InputStream input, boolean readMetadata, boolean enforceTransparency) throws IOException
      Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

      The current cache settings from getUseCacheand getCacheDirectory will be used to control caching in the ImageInputStream that is created.

      This method does not attempt to locate ImageReaders that can read directly from an InputStream; that may be accomplished using IIORegistry and ImageReaderSpi.

      This method does not close the provided InputStream after the read operation has completed; it is the responsibility of the caller to close the stream, if desired.

      Parameters:
      input - an InputStream to read from.
      readMetadata - if true, makes sure to read image metadata to detect transparency color for non translucent images, if any. In that case the color can be retrieved later through PROP_TRANSPARENCY_COLOR. Always considered true if enforceTransparency is also true
      enforceTransparency - if true, makes sure to read image metadata and, if the image does not provide an alpha channel but defines a TransparentColor metadata node, that the resulting image has a transparency set to TRANSLUCENT and uses the correct transparent color.
      Returns:
      a BufferedImage containing the decoded contents of the input, or null.
      Throws:
      IllegalArgumentException - if input is null.
      IOException - if an error occurs during reading.
      Since:
      7132
    • read

      public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency) throws IOException
      Returns a BufferedImage as the result of decoding a supplied URL with an ImageReader chosen automatically from among those currently registered. An InputStream is obtained from the URL, which is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

      The current cache settings from getUseCacheand getCacheDirectory will be used to control caching in the ImageInputStream that is created.

      This method does not attempt to locate ImageReaders that can read directly from a URL; that may be accomplished using IIORegistry and ImageReaderSpi.

      Parameters:
      input - a URL to read from.
      readMetadata - if true, makes sure to read image metadata to detect transparency color for non translucent images, if any. In that case the color can be retrieved later through PROP_TRANSPARENCY_COLOR. Always considered true if enforceTransparency is also true
      enforceTransparency - if true, makes sure to read image metadata and, if the image does not provide an alpha channel but defines a TransparentColor metadata node, that the resulting image has a transparency set to TRANSLUCENT and uses the correct transparent color.
      Returns:
      a BufferedImage containing the decoded contents of the input, or null.
      Throws:
      IllegalArgumentException - if input is null.
      IOException - if an error occurs during reading.
      Since:
      7132
    • read

      public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency, Function<ImageReader,ImageReadParam> readParamFunction) throws IOException
      Returns a BufferedImage as the result of decoding a supplied URL with an ImageReader chosen automatically from among those currently registered. An InputStream is obtained from the URL, which is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

      The current cache settings from getUseCacheand getCacheDirectory will be used to control caching in the ImageInputStream that is created.

      This method does not attempt to locate ImageReaders that can read directly from a URL; that may be accomplished using IIORegistry and ImageReaderSpi.

      Parameters:
      input - a URL to read from.
      readMetadata - if true, makes sure to read image metadata to detect transparency color for non translucent images, if any. In that case the color can be retrieved later through PROP_TRANSPARENCY_COLOR. Always considered true if enforceTransparency is also true
      enforceTransparency - if true, makes sure to read image metadata and, if the image does not provide an alpha channel but defines a TransparentColor metadata node, that the resulting image has a transparency set to TRANSLUCENT and uses the correct transparent color.
      readParamFunction - a function to compute the read parameters from the image reader
      Returns:
      a BufferedImage containing the decoded contents of the input, or null.
      Throws:
      IllegalArgumentException - if input is null.
      IOException - if an error occurs during reading.
      Since:
      17880
    • read

      public static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency) throws IOException
      Returns a BufferedImage as the result of decoding a supplied ImageInputStream with an ImageReader chosen automatically from among those currently registered. If no registered ImageReader claims to be able to read the stream, null is returned.

      Unlike most other methods in this class, this method does close the provided ImageInputStream after the read operation has completed, unless null is returned, in which case this method does not close the stream.

      Parameters:
      stream - an ImageInputStream to read from.
      readMetadata - if true, makes sure to read image metadata to detect transparency color for non translucent images, if any. In that case the color can be retrieved later through PROP_TRANSPARENCY_COLOR. Always considered true if enforceTransparency is also true
      enforceTransparency - if true, makes sure to read image metadata and, if the image does not provide an alpha channel but defines a TransparentColor metadata node, that the resulting image has a transparency set to TRANSLUCENT and uses the correct transparent color. For Java < 11 only.
      Returns:
      a BufferedImage containing the decoded contents of the input, or null.
      Throws:
      IllegalArgumentException - if stream is null.
      IOException - if an error occurs during reading.
      Since:
      7132
    • read

      private static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency, Function<ImageReader,ImageReadParam> readParamFunction) throws IOException
      Throws:
      IOException
    • getTransparentColor

      public static Color getTransparentColor(ColorModel model, ImageReader reader) throws IOException
      Returns the TransparentColor defined in image reader metadata.
      Parameters:
      model - The image color model
      reader - The image reader
      Returns:
      the TransparentColor defined in image reader metadata, or null
      Throws:
      IOException - if an error occurs during reading
      Since:
      7499
      See Also:
    • parseRGB

      private static Color parseRGB(String... s)
    • makeImageTransparent

      Returns a transparent version of the given image, based on the given transparent color.
      Parameters:
      bi - The image to convert
      color - The transparent color
      Returns:
      The same image as bi where all pixels of the given color are transparent. This resulting image has also the special property PROP_TRANSPARENCY_FORCED set to color
      Since:
      7132
      See Also:
    • isTransparencyForced

      public static boolean isTransparencyForced(BufferedImage bi)
      Determines if the transparency of the given BufferedImage has been enforced by a previous call to makeImageTransparent(java.awt.image.BufferedImage, java.awt.Color).
      Parameters:
      bi - The BufferedImage to test
      Returns:
      true if the transparency of bi has been enforced by a previous call to makeImageTransparent.
      Since:
      7132
      See Also:
    • hasTransparentColor

      public static boolean hasTransparentColor(BufferedImage bi)
      Determines if the given BufferedImage has a transparent color determined by a previous call to read(java.io.File, boolean, boolean).
      Parameters:
      bi - The BufferedImage to test
      Returns:
      true if bi has a transparent color determined by a previous call to read.
      Since:
      7132
      See Also:
    • shutdown

      public static void shutdown(boolean now)
      Shutdown background image fetcher.
      Parameters:
      now - if true, attempts to stop all actively executing tasks, halts the processing of waiting tasks. if false, initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted
      Since:
      8412
    • toBufferedImage

      public static BufferedImage toBufferedImage(Image image)
      Converts an Image to a BufferedImage instance.
      Parameters:
      image - image to convert
      Returns:
      a BufferedImage instance for the given Image.
      Since:
      13038
    • toBufferedImage

      public static BufferedImage toBufferedImage(Image image, Rectangle cropArea)
      Converts an Rectangle area of Image to a BufferedImage instance.
      Parameters:
      image - image to convert
      cropArea - rectangle to crop image with
      Returns:
      a BufferedImage instance for the cropped area of Image.
      Since:
      13127
    • createImageInputStream

      Throws:
      IOException
    • createBlankIcon

      Creates a blank icon of the given size.
      Parameters:
      size - image size
      Returns:
      a blank icon of the given size
      Since:
      13984
    • getSVGContext

      private static com.github.weisj.jsvg.parser.LoaderContext getSVGContext()
    • toString

      public String toString()
      Overrides:
      toString in class Object