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 {
// CHECKSTYLE.OFF: SingleSpaceSeparator
private static final String HTTP_PROTOCOL = "http://";
private static final String HTTPS_PROTOCOL = "https://";
private static final String WIKI_PROTOCOL = "wiki://";
// CHECKSTYLE.ON: SingleSpaceSeparator
/**
* 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 an Action */
SMALLICON(Main.pref.getInteger("iconsize.smallicon", 16)),
/** LARGE_ICON_KEY value of an Action */
LARGEICON(Main.pref.getInteger("iconsize.largeicon", 24)),
/** map icon */
MAP(Main.pref.getInteger("iconsize.map", 16)),
/** map icon maximum size */
MAPMAX(Main.pref.getInteger("iconsize.mapmax", 48)),
/** cursor icon size */
CURSOR(Main.pref.getInteger("iconsize.cursor", 32)),
/** cursor overlay icon size */
CURSOROVERLAY(CURSOR),
/** menu icon size */
MENU(SMALLICON),
/** menu icon size in popup menus
* @since 8323
*/
POPUPMENU(LARGEICON),
/** Layer list icon size
* @since 8323
*/
LAYER(Main.pref.getInteger("iconsize.layer", 16)),
/** Toolbar button icon size
* @since 9253
*/
TOOLBAR(LARGEICON),
/** Side button maximum height
* @since 9253
*/
SIDEBUTTON(Main.pref.getInteger("iconsize.sidebutton", 20)),
/** Settings tab icon size
* @since 9253
*/
SETTINGS_TAB(Main.pref.getInteger("iconsize.settingstab", 48)),
/**
* The default image size
* @since 9705
*/
DEFAULT(Main.pref.getInteger("iconsize.default", 24)),
/**
* Splash dialog logo size
* @since 10358
*/
SPLASH_LOGO(128, 129),
/**
* About dialog logo size
* @since 10358
*/
ABOUT_LOGO(256, 258);
private final int virtualWidth;
private final int virtualHeight;
ImageSizes(int imageSize) {
this.virtualWidth = imageSize;
this.virtualHeight = imageSize;
}
ImageSizes(int width, int height) {
this.virtualWidth = width;
this.virtualHeight = height;
}
ImageSizes(ImageSizes that) {
this.virtualWidth = that.virtualWidth;
this.virtualHeight = that.virtualHeight;
}
/**
* Returns the image width in virtual pixels
* @return the image width in virtual pixels
* @since 9705
*/
public int getVirtualWidth() {
return virtualWidth;
}
/**
* Returns the image height in virtual pixels
* @return the image height in virtual pixels
* @since 9705
*/
public int getVirtualHeight() {
return virtualHeight;
}
/**
* Returns the image width in pixels to use for display
* @return the image width in pixels to use for display
* @since 10484
*/
public int getAdjustedWidth() {
return GuiSizesHelper.getSizeDpiAdjusted(virtualWidth);
}
/**
* Returns the image height in pixels to use for display
* @return the image height in pixels to use for display
* @since 10484
*/
public int getAdjustedHeight() {
return GuiSizesHelper.getSizeDpiAdjusted(virtualHeight);
}
/**
* Returns the image size as dimension
* @return the image size as dimension
* @since 9705
*/
public Dimension getImageDimension() {
return new Dimension(virtualWidth, virtualHeight);
}
}
/**
* 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
if icon must be grayed out */
protected boolean isDisabled;
private static SVGUniverse svgUniverse;
/**
* The icon cache
*/
private static final Maptrue
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 (IOException e) {
Main.warn(e, 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;
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/jdk8u/jdk8u/jdk/file/dc4322602480/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