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(Config.getPref().getInt("iconsize.smallicon", 16)),
/** LARGE_ICON_KEY value of an Action */
LARGEICON(Config.getPref().getInt("iconsize.largeicon", 24)),
/** map icon */
MAP(Config.getPref().getInt("iconsize.map", 16)),
/** map icon maximum size */
MAPMAX(Config.getPref().getInt("iconsize.mapmax", 48)),
/** cursor icon size */
CURSOR(Config.getPref().getInt("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(Config.getPref().getInt("iconsize.layer", 16)),
/** Toolbar button icon size
* @since 9253
*/
TOOLBAR(LARGEICON),
/** Side button maximum height
* @since 9253
*/
SIDEBUTTON(Config.getPref().getInt("iconsize.sidebutton", 20)),
/** Settings tab icon size
* @since 9253
*/
SETTINGS_TAB(Config.getPref().getInt("iconsize.settingstab", 48)),
/**
* The default image size
* @since 9705
*/
DEFAULT(Config.getPref().getInt("iconsize.default", 24)),
/**
* Splash dialog logo size
* @since 10358
*/
SPLASH_LOGO(128, 129),
/**
* About dialog logo size
* @since 10358
*/
ABOUT_LOGO(256, 258),
/**
* Status line logo size
* @since 13369
*/
STATUSLINE(18, 18);
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";
/** set of class loaders to take images from */
protected static final Setnull
for missing image */
protected boolean optional;
/** true
if warnings should be suppressed */
protected boolean suppressWarnings;
/** ordered list of overlay images */
protected Listtrue
if icon must be grayed out */
protected boolean isDisabled;
/** true
if multi-resolution image is requested */
protected boolean multiResolution = true;
private static SVGUniverse svgUniverse;
/**
* The icon cache
*/
private static final Maphttp://
Id is not used for the cache.
* (A URL is unique anyway.)
* @param id the id for the cached image
* @return the current object, for convenience
*/
public ImageProvider setId(String id) {
this.id = id;
return this;
}
/**
* Specify a zip file where the image is located.
*
* (optional)
* @param archive zip file where the image is located
* @return the current object, for convenience
*/
public ImageProvider setArchive(File archive) {
this.archive = archive;
return this;
}
/**
* Specify a base path inside the zip file.
*
* The subdir and name will be relative to this path.
*
* (optional)
* @param inArchiveDir path inside the archive
* @return the current object, for convenience
*/
public ImageProvider setInArchiveDir(String inArchiveDir) {
this.inArchiveDir = inArchiveDir;
return this;
}
/**
* Add an overlay over the image. Multiple overlays are possible.
*
* @param overlay overlay image and placement specification
* @return the current object, for convenience
* @since 8095
*/
public ImageProvider addOverlay(ImageOverlay overlay) {
if (overlayInfo == null) {
overlayInfo = new LinkedList<>();
}
overlayInfo.add(overlay);
return this;
}
/**
* 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.)
* @param size final dimensions of the image
* @return the current object, for convenience
*/
public ImageProvider setSize(Dimension size) {
this.virtualWidth = size.width;
this.virtualHeight = size.height;
return this;
}
/**
* Set the dimensions of the image.
*
* If not specified, the original size of the image is used.
* @param size final dimensions of the image
* @return the current object, for convenience
* @since 7687
*/
public ImageProvider setSize(ImageSizes size) {
return setSize(size.getImageDimension());
}
/**
* Set the dimensions of the image.
*
* @param width final width of the image
* @param height final height of the image
* @return the current object, for convenience
* @since 10358
*/
public ImageProvider setSize(int width, int height) {
this.virtualWidth = width;
this.virtualHeight = height;
return this;
}
/**
* Set image width
* @param width final width of the image
* @return the current object, for convenience
* @see #setSize
*/
public ImageProvider setWidth(int width) {
this.virtualWidth = width;
return this;
}
/**
* Set image height
* @param height final height of the image
* @return the current object, for convenience
* @see #setSize
*/
public ImageProvider setHeight(int height) {
this.virtualHeight = height;
return this;
}
/**
* 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.
* @param maxSize maximum image size
* @return the current object, for convenience
*/
public ImageProvider setMaxSize(Dimension maxSize) {
this.virtualMaxWidth = maxSize.width;
this.virtualMaxHeight = maxSize.height;
return this;
}
/**
* 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.
*
* @param maxSize maximum image size
* @return the current object, for convenience
* @see #setMaxSize(Dimension)
*/
public ImageProvider resetMaxSize(Dimension maxSize) {
if (this.virtualMaxWidth == -1 || maxSize.width < this.virtualMaxWidth) {
this.virtualMaxWidth = maxSize.width;
}
if (this.virtualMaxHeight == -1 || maxSize.height < this.virtualMaxHeight) {
this.virtualMaxHeight = maxSize.height;
}
return this;
}
/**
* 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.
* @param size maximum image size
* @return the current object, for convenience
* @since 7687
*/
public ImageProvider setMaxSize(ImageSizes size) {
return setMaxSize(size.getImageDimension());
}
/**
* Convenience method, see {@link #setMaxSize(Dimension)}.
* @param maxSize maximum image size
* @return the current object, for convenience
*/
public ImageProvider setMaxSize(int maxSize) {
return this.setMaxSize(new Dimension(maxSize, maxSize));
}
/**
* Limit the maximum width of the image.
* @param maxWidth maximum image width
* @return the current object, for convenience
* @see #setMaxSize
*/
public ImageProvider setMaxWidth(int maxWidth) {
this.virtualMaxWidth = maxWidth;
return this;
}
/**
* Limit the maximum height of the image.
* @param maxHeight maximum image height
* @return the current object, for convenience
* @see #setMaxSize
*/
public ImageProvider setMaxHeight(int maxHeight) {
this.virtualMaxHeight = maxHeight;
return this;
}
/**
* 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.
*
* @param optional true, if JOSM should not throw a RuntimeException
* in case the image cannot be located.
* @return the current object, for convenience
*/
public ImageProvider setOptional(boolean optional) {
this.optional = optional;
return this;
}
/**
* Suppresses warning on the command line in case the image cannot be found.
*
* In combination with setOptional(true);
* @param suppressWarnings if true
warnings are suppressed
* @return the current object, for convenience
*/
public ImageProvider setSuppressWarnings(boolean suppressWarnings) {
this.suppressWarnings = suppressWarnings;
return this;
}
/**
* Add an additional class loader to search image for.
* @param additionalClassLoader class loader to add to the internal set
* @return {@code true} if the set changed as a result of the call
* @since 12870
*/
public static boolean addAdditionalClassLoader(ClassLoader additionalClassLoader) {
return classLoaders.add(additionalClassLoader);
}
/**
* Add a collection of additional class loaders to search image for.
* @param additionalClassLoaders class loaders to add to the internal set
* @return {@code true} if the set changed as a result of the call
* @since 12870
*/
public static boolean addAdditionalClassLoaders(Collectiontrue
).
*
* A java.awt.image.MultiResolutionImage
is a Java 9 {@link 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 {@link HiDPISupport#getBaseImage(java.awt.Image)} to extract the original image from a multi-resolution image. *
* See {@link HiDPISupport#processMRImage} for how to process the image without removing the multi-resolution magic.
* @param multiResolution true, if multi-resolution image is requested
* @return the current object, for convenience
*/
public ImageProvider setMultiResolution(boolean multiResolution) {
this.multiResolution = multiResolution;
return this;
}
/**
* Determines if this icon is located on a remote location (http, https, wiki).
* @return {@code true} if this icon is located on a remote location (http, https, wiki)
* @since 13250
*/
public boolean isRemote() {
return name.startsWith(HTTP_PROTOCOL) || name.startsWith(HTTPS_PROTOCOL) || name.startsWith(WIKI_PROTOCOL);
}
/**
* Execute the image request and scale result.
* @return the requested image or null if the request failed
*/
public ImageIcon get() {
ImageResource ir = getResource();
if (ir == null) {
return null;
} else if (Logging.isTraceEnabled()) {
Logging.trace("get {0} from {1}", this, Thread.currentThread());
}
if (virtualMaxWidth != -1 || virtualMaxHeight != -1)
return ir.getImageIconBounded(new Dimension(virtualMaxWidth, virtualMaxHeight), multiResolution);
else
return ir.getImageIcon(new Dimension(virtualWidth, virtualHeight), multiResolution);
}
/**
* Load the image in a background thread.
*
* This method returns immediately and runs the image request asynchronously.
* @param action the action that will deal with the image
*
* @return the future of the requested image
* @since 13252
*/
public CompletableFuture The current cache settings from Note that there is no This method does not attempt to locate
* The current cache settings from This method does not attempt to locate
* This method does not close the provided
* The current cache settings from This method does not attempt to locate
* Unlike most other methods in this class, this method does
* close the provided null
* @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) {
Logging.warn(e);
}
return img == null ? null : new ImageResource(img);
default:
throw new AssertionError("Unknown ImageType: "+type);
}
}
}
} catch (IOException e) {
Logging.log(Logging.LEVEL_WARN, tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()), e);
}
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()) {
try {
URI uri = getSvgUniverse().loadSVG(path);
svg = getSvgUniverse().getDiagram(uri);
} catch (SecurityException e) {
Logging.log(Logging.LEVEL_WARN, "Unable to read SVG", e);
}
}
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 (Logging.isDebugEnabled() && isTransparencyForced(img)) {
Logging.debug("Transparency has been forced for image {0}", path);
}
} catch (IOException e) {
Logging.log(Logging.LEVEL_WARN, "Unable to read image", e);
Logging.debug(e);
}
return img == null ? null : new ImageResource(img);
default:
throw new AssertionError();
}
}
private URL getImageUrl(String path, String name) {
if (path != null && path.startsWith("resource://")) {
String p = path.substring("resource://".length());
for (ClassLoader source : classLoaders) {
URL res;
if ((res = source.getResource(p + name)) != null)
return res;
}
} else {
File f = new File(path, name);
try {
if ((path != null || f.isAbsolute()) && f.exists())
return Utils.fileToURL(f);
} catch (SecurityException e) {
Logging.log(Logging.LEVEL_ERROR, "Unable to access image", e);
}
}
return null;
}
private URL getImageUrl(String imageName) {
URL u;
// Try passed directories first
if (dirs != null) {
for (String name : dirs) {
try {
u = getImageUrl(name, imageName);
if (u != null)
return u;
} catch (SecurityException e) {
Logging.log(Logging.LEVEL_WARN, tr(
"Failed to access directory ''{0}'' for security reasons. Exception was: {1}",
name, e.toString()), e);
}
}
}
// Try user-data directory
if (Config.getDirs() != null) {
File file = new File(Config.getDirs().getUserDataDirectory(false), "images");
String dir = file.getPath();
try {
dir = file.getAbsolutePath();
} catch (SecurityException e) {
Logging.debug(e);
}
try {
u = getImageUrl(dir, imageName);
if (u != null)
return u;
} catch (SecurityException e) {
Logging.log(Logging.LEVEL_WARN, tr(
"Failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
.toString()), e);
}
}
// Absolute path?
u = getImageUrl(null, imageName);
if (u != null)
return u;
// Try plugins and josm classloader
u = getImageUrl("resource://images/", imageName);
if (u != null)
return u;
// Try all other resource directories
if (Main.pref != null) {
for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
u = getImageUrl(location + "images", imageName);
if (u != null)
return u;
u = getImageUrl(location, imageName);
if (u != null)
return u;
}
}
return null;
}
/**
* Reads the wiki page on a certain file in html format in order to find the real image URL.
*
* @param base base URL for Wiki image
* @param fn filename of the Wiki image
* @return image URL for a Wiki image or null in case of error
*/
private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
try {
final XMLReader parser = Utils.newSafeSAXParser().getXMLReader();
parser.setContentHandler(new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if ("img".equalsIgnoreCase(localName)) {
String val = atts.getValue("src");
if (val.endsWith(fn))
throw new SAXReturnException(val); // parsing done, quit early
}
}
});
parser.setEntityResolver((publicId, systemId) -> new InputSource(new ByteArrayInputStream(new byte[0])));
try (CachedFile cf = new CachedFile(base + fn).setDestDir(
new File(Config.getDirs().getUserDataDirectory(true), "images").getPath());
InputStream is = cf.getInputStream()) {
parser.parse(new InputSource(is));
}
} catch (SAXReturnException e) {
Logging.trace(e);
return e.getResult();
} catch (IOException | SAXException | ParserConfigurationException e) {
Logging.warn("Parsing " + base + fn + " failed:\n" + e);
return null;
}
Logging.warn("Parsing " + base + fn + " failed: Unexpected content.");
return null;
}
/**
* Load a cursor with a given file name, optionally decorated with an overlay image.
*
* @param name the cursor image filename in "cursor" directory
* @param overlay optional overlay image
* @return cursor with a given file name, optionally decorated with an overlay image
*/
public static Cursor getCursor(String name, String overlay) {
ImageIcon img = get("cursor", name);
if (overlay != null) {
img = new ImageProvider("cursor", name).setMaxSize(ImageSizes.CURSOR)
.addOverlay(new ImageOverlay(new ImageProvider("cursor/modifier/" + overlay)
.setMaxSize(ImageSizes.CURSOROVERLAY))).get();
}
if (GraphicsEnvironment.isHeadless()) {
Logging.debug("Cursors are not available in headless mode. Returning null for '{0}'", name);
return null;
}
return Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
"crosshair".equals(name) ? new Point(10, 10) : new Point(3, 2), "Cursor");
}
/** 90 degrees in radians units */
private static final double DEGREE_90 = 90.0 * Math.PI / 180.0;
/**
* Creates a rotated version of the input image.
*
* @param img the image to be rotated.
* @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
* will mod it with 360 before using it. More over for caching performance, it will be rounded to
* an entire value between 0 and 360.
*
* @return the image after rotating.
* @since 6172
*/
public static Image createRotatedImage(Image img, double rotatedAngle) {
return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
}
/**
* Creates a rotated version of the input image.
*
* @param img the image to be rotated.
* @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
* will mod it with 360 before using it. More over for caching performance, it will be rounded to
* an entire value between 0 and 360.
* @param dimension ignored
* @return the image after rotating and scaling.
* @since 6172
*/
public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
CheckParameterUtil.ensureParameterNotNull(img, "img");
// convert rotatedAngle to an integer value from 0 to 360
Long angleLong = Math.round(rotatedAngle % 360);
Long originalAngle = rotatedAngle != 0 && angleLong == 0 ? Long.valueOf(360L) : angleLong;
synchronized (ROTATE_CACHE) {
MapBufferedImage
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.
*
* getUseCache
and
* getCacheDirectory
will be used to control caching in the
* ImageInputStream
that is created.
*
* read
method that takes a
* filename as a String
; use this method instead after
* creating a File
from the filename.
*
* 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 = 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.
*
* getUseCache
and
* getCacheDirectory
will be used to control caching in the
* ImageInputStream
that is created.
*
* ImageReader
s that can read directly from an
* InputStream
; that may be accomplished using
* IIORegistry
and ImageReaderSpi
.
*
* 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 = 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.
*
* getUseCache
and
* getCacheDirectory
will be used to control caching in the
* ImageInputStream
that is created.
*
* 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");
try (InputStream istream = Utils.openStream(input)) {
ImageInputStream stream = createImageInputStream(istream);
BufferedImage bi = read(stream, readMetadata, enforceTransparency);
if (bi == null) {
stream.close();
}
return bi;
} catch (SecurityException e) {
throw new IOException(e);
}
}
/**
* 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.
*
* 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