ImageIcon icon = new ImageProvider(name).setMaxSize(ImageSizes.MAP).get();
* (there are more options, see below)
*
* short form:
* ImageIcon icon = ImageProvider.get(name);
*
* @author imi
*/
public class ImageProvider {
private static final String HTTP_PROTOCOL = "http://";
private static final String HTTPS_PROTOCOL = "https://";
private static final String WIKI_PROTOCOL = "wiki://";
/**
* Position of an overlay icon
*/
public enum OverlayPosition {
/** North west */
NORTHWEST,
/** North east */
NORTHEAST,
/** South west */
SOUTHWEST,
/** South east */
SOUTHEAST
}
/**
* Supported image types
*/
public enum ImageType {
/** Scalable vector graphics */
SVG,
/** Everything else, e.g. png, gif (must be supported by Java) */
OTHER
}
/**
* Supported image sizes
* @since 7687
*/
public enum ImageSizes {
/** SMALL_ICON value of on Action */
SMALLICON,
/** LARGE_ICON_KEY value of on Action */
LARGEICON,
/** map icon */
MAP,
/** map icon maximum size */
MAPMAX,
/** cursor icon size */
CURSOR,
/** cursor overlay icon size */
CURSOROVERLAY,
/** menu icon size */
MENU,
/** menu icon size in popup menus
* @since 8323
*/
POPUPMENU,
/** Layer list icon size
* @since 8323
*/
LAYER,
/** Toolbar button icon size
* @since 9253
*/
TOOLBAR,
/** Side button maximum height
* @since 9253
*/
SIDEBUTTON
}
/**
* Property set on {@code BufferedImage} returned by {@link #makeImageTransparent}.
* @since 7132
*/
public static final String PROP_TRANSPARENCY_FORCED = "josm.transparency.forced";
/**
* Property set on {@code BufferedImage} returned by {@link #read} if metadata is required.
* @since 7132
*/
public static final String PROP_TRANSPARENCY_COLOR = "josm.transparency.color";
/** directories in which images are searched */
protected Collectionnull
for missing image */
protected boolean optional;
/** true
if warnings should be suppressed */
protected boolean suppressWarnings;
/** list of class loaders to take images from */
protected Collectiontrue
warnings are suppressed
* @return the current object, for convenience
*/
public ImageProvider setSuppressWarnings(boolean suppressWarnings) {
this.suppressWarnings = suppressWarnings;
return this;
}
/**
* Add a collection of additional class loaders to search image for.
* @param additionalClassLoaders class loaders to add to the internal list
* @return the current object, for convenience
*/
public ImageProvider setAdditionalClassLoaders(Collectionnull
* @param type data type of the image
* @return the requested image or null if the request failed
*/
private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
try (ZipFile zipFile = new ZipFile(archive, StandardCharsets.UTF_8)) {
if (inArchiveDir == null || ".".equals(inArchiveDir)) {
inArchiveDir = "";
} else if (!inArchiveDir.isEmpty()) {
inArchiveDir += '/';
}
String entryName = inArchiveDir + fullName;
ZipEntry entry = zipFile.getEntry(entryName);
if (entry != null) {
int size = (int) entry.getSize();
int offs = 0;
byte[] buf = new byte[size];
try (InputStream is = zipFile.getInputStream(entry)) {
switch (type) {
case SVG:
SVGDiagram svg = null;
synchronized (getSvgUniverse()) {
URI uri = getSvgUniverse().loadSVG(is, entryName);
svg = getSvgUniverse().getDiagram(uri);
}
return svg == null ? null : new ImageResource(svg);
case OTHER:
while (size > 0) {
int l = is.read(buf, offs, size);
offs += l;
size -= l;
}
BufferedImage img = null;
try {
img = read(new ByteArrayInputStream(buf), false, false);
} catch (IOException e) {
Main.warn(e);
}
return img == null ? null : new ImageResource(img);
default:
throw new AssertionError("Unknown ImageType: "+type);
}
}
}
} catch (Exception e) {
Main.warn(tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
}
return null;
}
/**
* Internal implementation of the image request for local images.
*
* @param path image file path
* @param type data type of the image
* @return the requested image or null if the request failed
*/
private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
switch (type) {
case SVG:
SVGDiagram svg = null;
synchronized (getSvgUniverse()) {
URI uri = getSvgUniverse().loadSVG(path);
svg = getSvgUniverse().getDiagram(uri);
}
return svg == null ? null : new ImageResource(svg);
case OTHER:
BufferedImage img = null;
try {
// See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
// This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
// hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/828c4fedd29f/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
img = read(path, false, true);
if (Main.isDebugEnabled() && isTransparencyForced(img)) {
Main.debug("Transparency has been forced for image "+path.toExternalForm());
}
} catch (IOException e) {
Main.warn(e);
}
return img == null ? null : new ImageResource(img);
default:
throw new AssertionError();
}
}
private static URL getImageUrl(String path, String name, CollectionBufferedImage
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 getUseCache
and
* 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
* ImageReader
s that can read directly from a
* File
; that may be accomplished using
* IIORegistry
and ImageReaderSpi
.
*
* @param input a File
to read from.
* @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color, if any.
* In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
* Always considered {@code true} if {@code enforceTransparency} is also {@code true}
* @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
* provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
* has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
*
* @return a BufferedImage
containing the decoded
* contents of the input, or null
.
*
* @throws IllegalArgumentException if input
is null
.
* @throws IOException if an error occurs during reading.
* @see BufferedImage#getProperty
* @since 7132
*/
public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException {
CheckParameterUtil.ensureParameterNotNull(input, "input");
if (!input.canRead()) {
throw new IIOException("Can't read input file!");
}
ImageInputStream stream = ImageIO.createImageInputStream(input);
if (stream == null) {
throw new IIOException("Can't create an ImageInputStream!");
}
BufferedImage bi = read(stream, readMetadata, enforceTransparency);
if (bi == null) {
stream.close();
}
return bi;
}
/**
* 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 getUseCache
and
* getCacheDirectory
will be used to control caching in the
* ImageInputStream
that is created.
*
*
This method does not attempt to locate
* ImageReader
s 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.
*
* @param input an InputStream
to read from.
* @param readMetadata if {@code 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 {@link #PROP_TRANSPARENCY_COLOR}.
* Always considered {@code true} if {@code enforceTransparency} is also {@code true}
* @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
* provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
* has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
*
* @return a BufferedImage
containing the decoded
* contents of the input, or null
.
*
* @throws IllegalArgumentException if input
is null
.
* @throws IOException if an error occurs during reading.
* @since 7132
*/
public static BufferedImage read(InputStream input, boolean readMetadata, boolean enforceTransparency) throws IOException {
CheckParameterUtil.ensureParameterNotNull(input, "input");
ImageInputStream stream = ImageIO.createImageInputStream(input);
BufferedImage bi = read(stream, readMetadata, enforceTransparency);
if (bi == null) {
stream.close();
}
return bi;
}
/**
* 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 getUseCache
and
* getCacheDirectory
will be used to control caching in the
* ImageInputStream
that is created.
*
*
This method does not attempt to locate
* ImageReader
s that can read directly from a
* URL
; that may be accomplished using
* IIORegistry
and ImageReaderSpi
.
*
* @param input a URL
to read from.
* @param readMetadata if {@code 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 {@link #PROP_TRANSPARENCY_COLOR}.
* Always considered {@code true} if {@code enforceTransparency} is also {@code true}
* @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
* provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
* has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
*
* @return a BufferedImage
containing the decoded
* contents of the input, or null
.
*
* @throws IllegalArgumentException if input
is null
.
* @throws IOException if an error occurs during reading.
* @since 7132
*/
public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency) throws IOException {
CheckParameterUtil.ensureParameterNotNull(input, "input");
InputStream istream = null;
try {
istream = input.openStream();
} catch (IOException e) {
throw new IIOException("Can't get input stream from URL!", e);
}
ImageInputStream stream = ImageIO.createImageInputStream(istream);
BufferedImage bi;
try {
bi = read(stream, readMetadata, enforceTransparency);
if (bi == null) {
stream.close();
}
} finally {
istream.close();
}
return bi;
}
/**
* 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.
*
* @param stream an ImageInputStream
to read from.
* @param readMetadata if {@code 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 {@link #PROP_TRANSPARENCY_COLOR}.
* Always considered {@code true} if {@code enforceTransparency} is also {@code true}
* @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
* provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
* has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
*
* @return a BufferedImage
containing the decoded
* contents of the input, or null
.
*
* @throws IllegalArgumentException if stream
is null
.
* @throws IOException if an error occurs during reading.
* @since 7132
*/
public static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency) throws IOException {
CheckParameterUtil.ensureParameterNotNull(stream, "stream");
Iterator