[6380] | 1 | // License: GPL. For details, see LICENSE file.
|
---|
[71] | 2 | package org.openstreetmap.josm.tools;
|
---|
[17] | 3 |
|
---|
[2017] | 4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
| 5 |
|
---|
[7132] | 6 | import java.awt.Color;
|
---|
[101] | 7 | import java.awt.Cursor;
|
---|
[4271] | 8 | import java.awt.Dimension;
|
---|
[17] | 9 | import java.awt.Graphics;
|
---|
[1295] | 10 | import java.awt.Graphics2D;
|
---|
[17] | 11 | import java.awt.GraphicsEnvironment;
|
---|
[79] | 12 | import java.awt.Image;
|
---|
[101] | 13 | import java.awt.Point;
|
---|
[1295] | 14 | import java.awt.RenderingHints;
|
---|
[79] | 15 | import java.awt.Toolkit;
|
---|
[7132] | 16 | import java.awt.Transparency;
|
---|
[17] | 17 | import java.awt.image.BufferedImage;
|
---|
[7132] | 18 | import java.awt.image.ColorModel;
|
---|
| 19 | import java.awt.image.FilteredImageSource;
|
---|
| 20 | import java.awt.image.ImageFilter;
|
---|
| 21 | import java.awt.image.ImageProducer;
|
---|
| 22 | import java.awt.image.RGBImageFilter;
|
---|
| 23 | import java.awt.image.WritableRaster;
|
---|
[4403] | 24 | import java.io.ByteArrayInputStream;
|
---|
[243] | 25 | import java.io.File;
|
---|
[2990] | 26 | import java.io.IOException;
|
---|
[2889] | 27 | import java.io.InputStream;
|
---|
[4713] | 28 | import java.io.StringReader;
|
---|
[4256] | 29 | import java.net.URI;
|
---|
[17] | 30 | import java.net.URL;
|
---|
[7082] | 31 | import java.nio.charset.StandardCharsets;
|
---|
[5033] | 32 | import java.util.ArrayList;
|
---|
[991] | 33 | import java.util.Arrays;
|
---|
[10746] | 34 | import java.util.Base64;
|
---|
[991] | 35 | import java.util.Collection;
|
---|
[17] | 36 | import java.util.HashMap;
|
---|
[7132] | 37 | import java.util.Hashtable;
|
---|
| 38 | import java.util.Iterator;
|
---|
[8095] | 39 | import java.util.LinkedList;
|
---|
| 40 | import java.util.List;
|
---|
[17] | 41 | import java.util.Map;
|
---|
[9691] | 42 | import java.util.TreeSet;
|
---|
[10714] | 43 | import java.util.concurrent.CompletableFuture;
|
---|
[5540] | 44 | import java.util.concurrent.ExecutorService;
|
---|
[5054] | 45 | import java.util.concurrent.Executors;
|
---|
[4713] | 46 | import java.util.regex.Matcher;
|
---|
| 47 | import java.util.regex.Pattern;
|
---|
[2889] | 48 | import java.util.zip.ZipEntry;
|
---|
| 49 | import java.util.zip.ZipFile;
|
---|
[4820] | 50 |
|
---|
[7132] | 51 | import javax.imageio.IIOException;
|
---|
[4938] | 52 | import javax.imageio.ImageIO;
|
---|
[7132] | 53 | import javax.imageio.ImageReadParam;
|
---|
| 54 | import javax.imageio.ImageReader;
|
---|
| 55 | import javax.imageio.metadata.IIOMetadata;
|
---|
| 56 | import javax.imageio.stream.ImageInputStream;
|
---|
[17] | 57 | import javax.swing.ImageIcon;
|
---|
[10741] | 58 | import javax.xml.parsers.ParserConfigurationException;
|
---|
[4820] | 59 |
|
---|
[21] | 60 | import org.openstreetmap.josm.Main;
|
---|
[10179] | 61 | import org.openstreetmap.josm.data.osm.DataSet;
|
---|
[8903] | 62 | import org.openstreetmap.josm.data.osm.OsmPrimitive;
|
---|
[1814] | 63 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
[8903] | 64 | import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
|
---|
| 65 | import org.openstreetmap.josm.gui.mappaint.Range;
|
---|
[9284] | 66 | import org.openstreetmap.josm.gui.mappaint.StyleElementList;
|
---|
[9278] | 67 | import org.openstreetmap.josm.gui.mappaint.styleelement.MapImage;
|
---|
[9454] | 68 | import org.openstreetmap.josm.gui.mappaint.styleelement.NodeElement;
|
---|
[9278] | 69 | import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
|
---|
[9265] | 70 | import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
|
---|
| 71 | import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
|
---|
[10358] | 72 | import org.openstreetmap.josm.gui.util.GuiSizesHelper;
|
---|
[7313] | 73 | import org.openstreetmap.josm.io.CachedFile;
|
---|
[3874] | 74 | import org.openstreetmap.josm.plugins.PluginHandler;
|
---|
[7132] | 75 | import org.w3c.dom.Element;
|
---|
| 76 | import org.w3c.dom.Node;
|
---|
[7134] | 77 | import org.w3c.dom.NodeList;
|
---|
[4403] | 78 | import org.xml.sax.Attributes;
|
---|
| 79 | import org.xml.sax.InputSource;
|
---|
| 80 | import org.xml.sax.SAXException;
|
---|
| 81 | import org.xml.sax.XMLReader;
|
---|
| 82 | import org.xml.sax.helpers.DefaultHandler;
|
---|
[4938] | 83 |
|
---|
[4403] | 84 | import com.kitfox.svg.SVGDiagram;
|
---|
[10212] | 85 | import com.kitfox.svg.SVGException;
|
---|
[4403] | 86 | import com.kitfox.svg.SVGUniverse;
|
---|
| 87 |
|
---|
[17] | 88 | /**
|
---|
[4271] | 89 | * Helper class to support the application with images.
|
---|
[4721] | 90 | *
|
---|
| 91 | * How to use:
|
---|
| 92 | *
|
---|
[8095] | 93 | * <code>ImageIcon icon = new ImageProvider(name).setMaxSize(ImageSizes.MAP).get();</code>
|
---|
[4721] | 94 | * (there are more options, see below)
|
---|
| 95 | *
|
---|
| 96 | * short form:
|
---|
| 97 | * <code>ImageIcon icon = ImageProvider.get(name);</code>
|
---|
| 98 | *
|
---|
[17] | 99 | * @author imi
|
---|
| 100 | */
|
---|
| 101 | public class ImageProvider {
|
---|
| 102 |
|
---|
[10378] | 103 | // CHECKSTYLE.OFF: SingleSpaceSeparator
|
---|
[7748] | 104 | private static final String HTTP_PROTOCOL = "http://";
|
---|
| 105 | private static final String HTTPS_PROTOCOL = "https://";
|
---|
| 106 | private static final String WIKI_PROTOCOL = "wiki://";
|
---|
[10378] | 107 | // CHECKSTYLE.ON: SingleSpaceSeparator
|
---|
[7748] | 108 |
|
---|
[1169] | 109 | /**
|
---|
[6172] | 110 | * Supported image types
|
---|
| 111 | */
|
---|
[8836] | 112 | public enum ImageType {
|
---|
[6172] | 113 | /** Scalable vector graphics */
|
---|
| 114 | SVG,
|
---|
| 115 | /** Everything else, e.g. png, gif (must be supported by Java) */
|
---|
| 116 | OTHER
|
---|
[4256] | 117 | }
|
---|
| 118 |
|
---|
[7132] | 119 | /**
|
---|
[7687] | 120 | * Supported image sizes
|
---|
| 121 | * @since 7687
|
---|
| 122 | */
|
---|
[8836] | 123 | public enum ImageSizes {
|
---|
[9949] | 124 | /** SMALL_ICON value of an Action */
|
---|
[9705] | 125 | SMALLICON(Main.pref.getInteger("iconsize.smallicon", 16)),
|
---|
[9949] | 126 | /** LARGE_ICON_KEY value of an Action */
|
---|
[9705] | 127 | LARGEICON(Main.pref.getInteger("iconsize.largeicon", 24)),
|
---|
[8095] | 128 | /** map icon */
|
---|
[9705] | 129 | MAP(Main.pref.getInteger("iconsize.map", 16)),
|
---|
[8095] | 130 | /** map icon maximum size */
|
---|
[9705] | 131 | MAPMAX(Main.pref.getInteger("iconsize.mapmax", 48)),
|
---|
[8323] | 132 | /** cursor icon size */
|
---|
[9705] | 133 | CURSOR(Main.pref.getInteger("iconsize.cursor", 32)),
|
---|
[8323] | 134 | /** cursor overlay icon size */
|
---|
[10358] | 135 | CURSOROVERLAY(CURSOR),
|
---|
[8323] | 136 | /** menu icon size */
|
---|
[10358] | 137 | MENU(SMALLICON),
|
---|
[8323] | 138 | /** menu icon size in popup menus
|
---|
| 139 | * @since 8323
|
---|
| 140 | */
|
---|
[10358] | 141 | POPUPMENU(LARGEICON),
|
---|
[8323] | 142 | /** Layer list icon size
|
---|
| 143 | * @since 8323
|
---|
| 144 | */
|
---|
[9705] | 145 | LAYER(Main.pref.getInteger("iconsize.layer", 16)),
|
---|
[9253] | 146 | /** Toolbar button icon size
|
---|
| 147 | * @since 9253
|
---|
| 148 | */
|
---|
[10358] | 149 | TOOLBAR(LARGEICON),
|
---|
[9253] | 150 | /** Side button maximum height
|
---|
| 151 | * @since 9253
|
---|
| 152 | */
|
---|
[9705] | 153 | SIDEBUTTON(Main.pref.getInteger("iconsize.sidebutton", 20)),
|
---|
[10358] | 154 | /** Settings tab icon size
|
---|
| 155 | * @since 9253
|
---|
| 156 | */
|
---|
| 157 | SETTINGS_TAB(Main.pref.getInteger("iconsize.settingstab", 48)),
|
---|
[9705] | 158 | /**
|
---|
| 159 | * The default image size
|
---|
| 160 | * @since 9705
|
---|
| 161 | */
|
---|
[10358] | 162 | DEFAULT(Main.pref.getInteger("iconsize.default", 24)),
|
---|
| 163 | /**
|
---|
| 164 | * Splash dialog logo size
|
---|
| 165 | * @since 10358
|
---|
| 166 | */
|
---|
| 167 | SPLASH_LOGO(128, 129),
|
---|
| 168 | /**
|
---|
| 169 | * About dialog logo size
|
---|
| 170 | * @since 10358
|
---|
| 171 | */
|
---|
| 172 | ABOUT_LOGO(256, 258);
|
---|
[9705] | 173 |
|
---|
[10358] | 174 | private final int virtualWidth;
|
---|
| 175 | private final int virtualHeight;
|
---|
[9705] | 176 |
|
---|
| 177 | ImageSizes(int imageSize) {
|
---|
[10358] | 178 | this.virtualWidth = imageSize;
|
---|
| 179 | this.virtualHeight = imageSize;
|
---|
[9705] | 180 | }
|
---|
| 181 |
|
---|
[10358] | 182 | ImageSizes(int width, int height) {
|
---|
| 183 | this.virtualWidth = width;
|
---|
| 184 | this.virtualHeight = height;
|
---|
| 185 | }
|
---|
| 186 |
|
---|
| 187 | ImageSizes(ImageSizes that) {
|
---|
| 188 | this.virtualWidth = that.virtualWidth;
|
---|
| 189 | this.virtualHeight = that.virtualHeight;
|
---|
| 190 | }
|
---|
| 191 |
|
---|
[9705] | 192 | /**
|
---|
[10358] | 193 | * Returns the image width in virtual pixels
|
---|
| 194 | * @return the image width in virtual pixels
|
---|
[10484] | 195 | * @since 9705
|
---|
[10358] | 196 | */
|
---|
| 197 | public int getVirtualWidth() {
|
---|
| 198 | return virtualWidth;
|
---|
| 199 | }
|
---|
| 200 |
|
---|
| 201 | /**
|
---|
| 202 | * Returns the image height in virtual pixels
|
---|
| 203 | * @return the image height in virtual pixels
|
---|
[9827] | 204 | * @since 9705
|
---|
[9705] | 205 | */
|
---|
[10358] | 206 | public int getVirtualHeight() {
|
---|
| 207 | return virtualHeight;
|
---|
[9705] | 208 | }
|
---|
| 209 |
|
---|
| 210 | /**
|
---|
[10484] | 211 | * Returns the image width in pixels to use for display
|
---|
| 212 | * @return the image width in pixels to use for display
|
---|
| 213 | * @since 10484
|
---|
| 214 | */
|
---|
| 215 | public int getAdjustedWidth() {
|
---|
[10485] | 216 | return GuiSizesHelper.getSizeDpiAdjusted(virtualWidth);
|
---|
[10484] | 217 | }
|
---|
| 218 |
|
---|
| 219 | /**
|
---|
| 220 | * Returns the image height in pixels to use for display
|
---|
| 221 | * @return the image height in pixels to use for display
|
---|
| 222 | * @since 10484
|
---|
| 223 | */
|
---|
| 224 | public int getAdjustedHeight() {
|
---|
[10485] | 225 | return GuiSizesHelper.getSizeDpiAdjusted(virtualHeight);
|
---|
[10484] | 226 | }
|
---|
| 227 |
|
---|
| 228 | /**
|
---|
[9705] | 229 | * Returns the image size as dimension
|
---|
| 230 | * @return the image size as dimension
|
---|
[9827] | 231 | * @since 9705
|
---|
[9705] | 232 | */
|
---|
| 233 | public Dimension getImageDimension() {
|
---|
[10358] | 234 | return new Dimension(virtualWidth, virtualHeight);
|
---|
[9705] | 235 | }
|
---|
[7687] | 236 | }
|
---|
| 237 |
|
---|
| 238 | /**
|
---|
[7132] | 239 | * Property set on {@code BufferedImage} returned by {@link #makeImageTransparent}.
|
---|
| 240 | * @since 7132
|
---|
| 241 | */
|
---|
[8286] | 242 | public static final String PROP_TRANSPARENCY_FORCED = "josm.transparency.forced";
|
---|
[7132] | 243 |
|
---|
| 244 | /**
|
---|
| 245 | * Property set on {@code BufferedImage} returned by {@link #read} if metadata is required.
|
---|
| 246 | * @since 7132
|
---|
| 247 | */
|
---|
[8286] | 248 | public static final String PROP_TRANSPARENCY_COLOR = "josm.transparency.color";
|
---|
[7132] | 249 |
|
---|
[8095] | 250 | /** directories in which images are searched */
|
---|
[4721] | 251 | protected Collection<String> dirs;
|
---|
[8095] | 252 | /** caching identifier */
|
---|
[4721] | 253 | protected String id;
|
---|
[8095] | 254 | /** sub directory the image can be found in */
|
---|
[4721] | 255 | protected String subdir;
|
---|
[8095] | 256 | /** image file name */
|
---|
[4721] | 257 | protected String name;
|
---|
[8095] | 258 | /** archive file to take image from */
|
---|
[4721] | 259 | protected File archive;
|
---|
[8095] | 260 | /** directory inside the archive */
|
---|
[6148] | 261 | protected String inArchiveDir;
|
---|
[10358] | 262 | /** virtual width of the resulting image, -1 when original image data should be used */
|
---|
| 263 | protected int virtualWidth = -1;
|
---|
| 264 | /** virtual height of the resulting image, -1 when original image data should be used */
|
---|
| 265 | protected int virtualHeight = -1;
|
---|
| 266 | /** virtual maximum width of the resulting image, -1 for no restriction */
|
---|
| 267 | protected int virtualMaxWidth = -1;
|
---|
| 268 | /** virtual maximum height of the resulting image, -1 for no restriction */
|
---|
| 269 | protected int virtualMaxHeight = -1;
|
---|
[8095] | 270 | /** In case of errors do not throw exception but return <code>null</code> for missing image */
|
---|
[4721] | 271 | protected boolean optional;
|
---|
[8095] | 272 | /** <code>true</code> if warnings should be suppressed */
|
---|
[5055] | 273 | protected boolean suppressWarnings;
|
---|
[8095] | 274 | /** list of class loaders to take images from */
|
---|
[5055] | 275 | protected Collection<ClassLoader> additionalClassLoaders;
|
---|
[8095] | 276 | /** ordered list of overlay images */
|
---|
[8840] | 277 | protected List<ImageOverlay> overlayInfo;
|
---|
[10428] | 278 | /** <code>true</code> if icon must be grayed out */
|
---|
[10755] | 279 | protected boolean isDisabled;
|
---|
[4721] | 280 |
|
---|
| 281 | private static SVGUniverse svgUniverse;
|
---|
| 282 |
|
---|
[1169] | 283 | /**
|
---|
| 284 | * The icon cache
|
---|
| 285 | */
|
---|
[7005] | 286 | private static final Map<String, ImageResource> cache = new HashMap<>();
|
---|
[93] | 287 |
|
---|
[6172] | 288 | /**
|
---|
| 289 | * Caches the image data for rotated versions of the same image.
|
---|
| 290 | */
|
---|
[7005] | 291 | private static final Map<Image, Map<Long, ImageResource>> ROTATE_CACHE = new HashMap<>();
|
---|
[5054] | 292 |
|
---|
[8734] | 293 | private static final ExecutorService IMAGE_FETCHER =
|
---|
| 294 | Executors.newSingleThreadExecutor(Utils.newThreadFactory("image-fetcher-%d", Thread.NORM_PRIORITY));
|
---|
[6172] | 295 |
|
---|
[7693] | 296 | /**
|
---|
[6172] | 297 | * Constructs a new {@code ImageProvider} from a filename in a given directory.
|
---|
[8095] | 298 | * @param subdir subdirectory the image lies in
|
---|
| 299 | * @param name the name of the image. If it does not end with '.png' or '.svg',
|
---|
| 300 | * both extensions are tried.
|
---|
[4721] | 301 | */
|
---|
| 302 | public ImageProvider(String subdir, String name) {
|
---|
| 303 | this.subdir = subdir;
|
---|
| 304 | this.name = name;
|
---|
| 305 | }
|
---|
| 306 |
|
---|
[6172] | 307 | /**
|
---|
| 308 | * Constructs a new {@code ImageProvider} from a filename.
|
---|
[8095] | 309 | * @param name the name of the image. If it does not end with '.png' or '.svg',
|
---|
| 310 | * both extensions are tried.
|
---|
[6172] | 311 | */
|
---|
[4721] | 312 | public ImageProvider(String name) {
|
---|
| 313 | this.name = name;
|
---|
| 314 | }
|
---|
| 315 |
|
---|
| 316 | /**
|
---|
[8097] | 317 | * Constructs a new {@code ImageProvider} from an existing one.
|
---|
| 318 | * @param image the existing image provider to be copied
|
---|
| 319 | * @since 8095
|
---|
| 320 | */
|
---|
| 321 | public ImageProvider(ImageProvider image) {
|
---|
| 322 | this.dirs = image.dirs;
|
---|
| 323 | this.id = image.id;
|
---|
| 324 | this.subdir = image.subdir;
|
---|
| 325 | this.name = image.name;
|
---|
| 326 | this.archive = image.archive;
|
---|
| 327 | this.inArchiveDir = image.inArchiveDir;
|
---|
[10358] | 328 | this.virtualWidth = image.virtualWidth;
|
---|
| 329 | this.virtualHeight = image.virtualHeight;
|
---|
| 330 | this.virtualMaxWidth = image.virtualMaxWidth;
|
---|
| 331 | this.virtualMaxHeight = image.virtualMaxHeight;
|
---|
[8097] | 332 | this.optional = image.optional;
|
---|
| 333 | this.suppressWarnings = image.suppressWarnings;
|
---|
| 334 | this.additionalClassLoaders = image.additionalClassLoaders;
|
---|
| 335 | this.overlayInfo = image.overlayInfo;
|
---|
[10428] | 336 | this.isDisabled = image.isDisabled;
|
---|
[8097] | 337 | }
|
---|
| 338 |
|
---|
| 339 | /**
|
---|
[4721] | 340 | * Directories to look for the image.
|
---|
[6172] | 341 | * @param dirs The directories to look for.
|
---|
| 342 | * @return the current object, for convenience
|
---|
[4721] | 343 | */
|
---|
| 344 | public ImageProvider setDirs(Collection<String> dirs) {
|
---|
| 345 | this.dirs = dirs;
|
---|
| 346 | return this;
|
---|
| 347 | }
|
---|
| 348 |
|
---|
| 349 | /**
|
---|
[5275] | 350 | * Set an id used for caching.
|
---|
| 351 | * If name starts with <tt>http://</tt> Id is not used for the cache.
|
---|
| 352 | * (A URL is unique anyway.)
|
---|
[8095] | 353 | * @param id the id for the cached image
|
---|
[6172] | 354 | * @return the current object, for convenience
|
---|
[4721] | 355 | */
|
---|
| 356 | public ImageProvider setId(String id) {
|
---|
| 357 | this.id = id;
|
---|
| 358 | return this;
|
---|
| 359 | }
|
---|
| 360 |
|
---|
| 361 | /**
|
---|
[5275] | 362 | * Specify a zip file where the image is located.
|
---|
| 363 | *
|
---|
| 364 | * (optional)
|
---|
[8304] | 365 | * @param archive zip file where the image is located
|
---|
[6172] | 366 | * @return the current object, for convenience
|
---|
[4721] | 367 | */
|
---|
| 368 | public ImageProvider setArchive(File archive) {
|
---|
| 369 | this.archive = archive;
|
---|
| 370 | return this;
|
---|
| 371 | }
|
---|
| 372 |
|
---|
| 373 | /**
|
---|
[6148] | 374 | * Specify a base path inside the zip file.
|
---|
| 375 | *
|
---|
| 376 | * The subdir and name will be relative to this path.
|
---|
| 377 | *
|
---|
| 378 | * (optional)
|
---|
[8095] | 379 | * @param inArchiveDir path inside the archive
|
---|
[6172] | 380 | * @return the current object, for convenience
|
---|
[6148] | 381 | */
|
---|
| 382 | public ImageProvider setInArchiveDir(String inArchiveDir) {
|
---|
| 383 | this.inArchiveDir = inArchiveDir;
|
---|
| 384 | return this;
|
---|
| 385 | }
|
---|
| 386 |
|
---|
| 387 | /**
|
---|
[8095] | 388 | * Add an overlay over the image. Multiple overlays are possible.
|
---|
| 389 | *
|
---|
| 390 | * @param overlay overlay image and placement specification
|
---|
| 391 | * @return the current object, for convenience
|
---|
| 392 | * @since 8095
|
---|
| 393 | */
|
---|
| 394 | public ImageProvider addOverlay(ImageOverlay overlay) {
|
---|
| 395 | if (overlayInfo == null) {
|
---|
[9070] | 396 | overlayInfo = new LinkedList<>();
|
---|
[8095] | 397 | }
|
---|
| 398 | overlayInfo.add(overlay);
|
---|
| 399 | return this;
|
---|
| 400 | }
|
---|
| 401 |
|
---|
| 402 | /**
|
---|
[5275] | 403 | * Set the dimensions of the image.
|
---|
[4721] | 404 | *
|
---|
| 405 | * If not specified, the original size of the image is used.
|
---|
| 406 | * The width part of the dimension can be -1. Then it will only set the height but
|
---|
| 407 | * keep the aspect ratio. (And the other way around.)
|
---|
[8095] | 408 | * @param size final dimensions of the image
|
---|
[6172] | 409 | * @return the current object, for convenience
|
---|
[4721] | 410 | */
|
---|
| 411 | public ImageProvider setSize(Dimension size) {
|
---|
[10358] | 412 | this.virtualWidth = size.width;
|
---|
| 413 | this.virtualHeight = size.height;
|
---|
[4721] | 414 | return this;
|
---|
| 415 | }
|
---|
| 416 |
|
---|
| 417 | /**
|
---|
[7687] | 418 | * Set the dimensions of the image.
|
---|
| 419 | *
|
---|
| 420 | * If not specified, the original size of the image is used.
|
---|
[8095] | 421 | * @param size final dimensions of the image
|
---|
[7687] | 422 | * @return the current object, for convenience
|
---|
| 423 | * @since 7687
|
---|
| 424 | */
|
---|
| 425 | public ImageProvider setSize(ImageSizes size) {
|
---|
[9705] | 426 | return setSize(size.getImageDimension());
|
---|
[7687] | 427 | }
|
---|
| 428 |
|
---|
| 429 | /**
|
---|
[10358] | 430 | * Set the dimensions of the image.
|
---|
| 431 | *
|
---|
| 432 | * @param width final width of the image
|
---|
| 433 | * @param height final height of the image
|
---|
| 434 | * @return the current object, for convenience
|
---|
| 435 | * @since 10358
|
---|
| 436 | */
|
---|
| 437 | public ImageProvider setSize(int width, int height) {
|
---|
| 438 | this.virtualWidth = width;
|
---|
| 439 | this.virtualHeight = height;
|
---|
| 440 | return this;
|
---|
| 441 | }
|
---|
| 442 |
|
---|
| 443 | /**
|
---|
[8095] | 444 | * Set image width
|
---|
| 445 | * @param width final width of the image
|
---|
[8459] | 446 | * @return the current object, for convenience
|
---|
[5275] | 447 | * @see #setSize
|
---|
[4721] | 448 | */
|
---|
| 449 | public ImageProvider setWidth(int width) {
|
---|
[10358] | 450 | this.virtualWidth = width;
|
---|
[4721] | 451 | return this;
|
---|
| 452 | }
|
---|
| 453 |
|
---|
| 454 | /**
|
---|
[8095] | 455 | * Set image height
|
---|
| 456 | * @param height final height of the image
|
---|
[8459] | 457 | * @return the current object, for convenience
|
---|
[5275] | 458 | * @see #setSize
|
---|
[4721] | 459 | */
|
---|
| 460 | public ImageProvider setHeight(int height) {
|
---|
[10358] | 461 | this.virtualHeight = height;
|
---|
[4721] | 462 | return this;
|
---|
| 463 | }
|
---|
| 464 |
|
---|
| 465 | /**
|
---|
[5275] | 466 | * Limit the maximum size of the image.
|
---|
[4721] | 467 | *
|
---|
| 468 | * It will shrink the image if necessary, but keep the aspect ratio.
|
---|
| 469 | * The given width or height can be -1 which means this direction is not bounded.
|
---|
| 470 | *
|
---|
| 471 | * 'size' and 'maxSize' are not compatible, you should set only one of them.
|
---|
[8095] | 472 | * @param maxSize maximum image size
|
---|
[6172] | 473 | * @return the current object, for convenience
|
---|
[4721] | 474 | */
|
---|
| 475 | public ImageProvider setMaxSize(Dimension maxSize) {
|
---|
[10358] | 476 | this.virtualMaxWidth = maxSize.width;
|
---|
| 477 | this.virtualMaxHeight = maxSize.height;
|
---|
[4721] | 478 | return this;
|
---|
| 479 | }
|
---|
[6070] | 480 |
|
---|
[5543] | 481 | /**
|
---|
[7687] | 482 | * Limit the maximum size of the image.
|
---|
| 483 | *
|
---|
| 484 | * It will shrink the image if necessary, but keep the aspect ratio.
|
---|
| 485 | * The given width or height can be -1 which means this direction is not bounded.
|
---|
| 486 | *
|
---|
[8097] | 487 | * This function sets value using the most restrictive of the new or existing set of
|
---|
| 488 | * values.
|
---|
| 489 | *
|
---|
| 490 | * @param maxSize maximum image size
|
---|
| 491 | * @return the current object, for convenience
|
---|
| 492 | * @see #setMaxSize(Dimension)
|
---|
| 493 | */
|
---|
| 494 | public ImageProvider resetMaxSize(Dimension maxSize) {
|
---|
[10358] | 495 | if (this.virtualMaxWidth == -1 || maxSize.width < this.virtualMaxWidth) {
|
---|
| 496 | this.virtualMaxWidth = maxSize.width;
|
---|
[8097] | 497 | }
|
---|
[10358] | 498 | if (this.virtualMaxHeight == -1 || maxSize.height < this.virtualMaxHeight) {
|
---|
| 499 | this.virtualMaxHeight = maxSize.height;
|
---|
[8097] | 500 | }
|
---|
| 501 | return this;
|
---|
| 502 | }
|
---|
| 503 |
|
---|
| 504 | /**
|
---|
| 505 | * Limit the maximum size of the image.
|
---|
| 506 | *
|
---|
| 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 | *
|
---|
[7687] | 510 | * 'size' and 'maxSize' are not compatible, you should set only one of them.
|
---|
[8095] | 511 | * @param size maximum image size
|
---|
[7687] | 512 | * @return the current object, for convenience
|
---|
| 513 | * @since 7687
|
---|
| 514 | */
|
---|
| 515 | public ImageProvider setMaxSize(ImageSizes size) {
|
---|
[9705] | 516 | return setMaxSize(size.getImageDimension());
|
---|
[7687] | 517 | }
|
---|
| 518 |
|
---|
| 519 | /**
|
---|
[5543] | 520 | * Convenience method, see {@link #setMaxSize(Dimension)}.
|
---|
[8095] | 521 | * @param maxSize maximum image size
|
---|
[6172] | 522 | * @return the current object, for convenience
|
---|
[5543] | 523 | */
|
---|
| 524 | public ImageProvider setMaxSize(int maxSize) {
|
---|
| 525 | return this.setMaxSize(new Dimension(maxSize, maxSize));
|
---|
| 526 | }
|
---|
[4721] | 527 |
|
---|
| 528 | /**
|
---|
[8095] | 529 | * Limit the maximum width of the image.
|
---|
| 530 | * @param maxWidth maximum image width
|
---|
[8419] | 531 | * @return the current object, for convenience
|
---|
[5275] | 532 | * @see #setMaxSize
|
---|
[4721] | 533 | */
|
---|
| 534 | public ImageProvider setMaxWidth(int maxWidth) {
|
---|
[10358] | 535 | this.virtualMaxWidth = maxWidth;
|
---|
[4721] | 536 | return this;
|
---|
| 537 | }
|
---|
| 538 |
|
---|
| 539 | /**
|
---|
[8095] | 540 | * Limit the maximum height of the image.
|
---|
| 541 | * @param maxHeight maximum image height
|
---|
[8419] | 542 | * @return the current object, for convenience
|
---|
[5275] | 543 | * @see #setMaxSize
|
---|
[4721] | 544 | */
|
---|
| 545 | public ImageProvider setMaxHeight(int maxHeight) {
|
---|
[10358] | 546 | this.virtualMaxHeight = maxHeight;
|
---|
[4721] | 547 | return this;
|
---|
| 548 | }
|
---|
| 549 |
|
---|
| 550 | /**
|
---|
[5275] | 551 | * Decide, if an exception should be thrown, when the image cannot be located.
|
---|
[4721] | 552 | *
|
---|
[5275] | 553 | * Set to true, when the image URL comes from user data and the image may be missing.
|
---|
| 554 | *
|
---|
| 555 | * @param optional true, if JOSM should <b>not</b> throw a RuntimeException
|
---|
| 556 | * in case the image cannot be located.
|
---|
| 557 | * @return the current object, for convenience
|
---|
[4721] | 558 | */
|
---|
| 559 | public ImageProvider setOptional(boolean optional) {
|
---|
| 560 | this.optional = optional;
|
---|
| 561 | return this;
|
---|
| 562 | }
|
---|
| 563 |
|
---|
| 564 | /**
|
---|
[5055] | 565 | * Suppresses warning on the command line in case the image cannot be found.
|
---|
| 566 | *
|
---|
| 567 | * In combination with setOptional(true);
|
---|
[8095] | 568 | * @param suppressWarnings if <code>true</code> warnings are suppressed
|
---|
[6172] | 569 | * @return the current object, for convenience
|
---|
[4721] | 570 | */
|
---|
[5056] | 571 | public ImageProvider setSuppressWarnings(boolean suppressWarnings) {
|
---|
[5055] | 572 | this.suppressWarnings = suppressWarnings;
|
---|
| 573 | return this;
|
---|
[5027] | 574 | }
|
---|
[5033] | 575 |
|
---|
[5027] | 576 | /**
|
---|
[5055] | 577 | * Add a collection of additional class loaders to search image for.
|
---|
[8095] | 578 | * @param additionalClassLoaders class loaders to add to the internal list
|
---|
[6172] | 579 | * @return the current object, for convenience
|
---|
[5027] | 580 | */
|
---|
[5055] | 581 | public ImageProvider setAdditionalClassLoaders(Collection<ClassLoader> additionalClassLoaders) {
|
---|
| 582 | this.additionalClassLoaders = additionalClassLoaders;
|
---|
| 583 | return this;
|
---|
[5033] | 584 | }
|
---|
| 585 |
|
---|
| 586 | /**
|
---|
[10428] | 587 | * Set, if image must be filtered to grayscale so it will look like disabled icon.
|
---|
| 588 | *
|
---|
| 589 | * @param disabled true, if image must be grayed out for disabled state
|
---|
| 590 | * @return the current object, for convenience
|
---|
| 591 | * @since 10428
|
---|
| 592 | */
|
---|
| 593 | public ImageProvider setDisabled(boolean disabled) {
|
---|
| 594 | this.isDisabled = disabled;
|
---|
| 595 | return this;
|
---|
| 596 | }
|
---|
| 597 |
|
---|
| 598 | /**
|
---|
[7693] | 599 | * Execute the image request and scale result.
|
---|
| 600 | * @return the requested image or null if the request failed
|
---|
| 601 | */
|
---|
| 602 | public ImageIcon get() {
|
---|
| 603 | ImageResource ir = getResource();
|
---|
[10428] | 604 |
|
---|
| 605 | if (ir == null) {
|
---|
[7695] | 606 | return null;
|
---|
[10428] | 607 | }
|
---|
[10358] | 608 | if (virtualMaxWidth != -1 || virtualMaxHeight != -1)
|
---|
| 609 | return ir.getImageIconBounded(new Dimension(virtualMaxWidth, virtualMaxHeight));
|
---|
[7693] | 610 | else
|
---|
[10358] | 611 | return ir.getImageIcon(new Dimension(virtualWidth, virtualHeight));
|
---|
[7693] | 612 | }
|
---|
| 613 |
|
---|
| 614 | /**
|
---|
[10714] | 615 | * Load the image in a background thread.
|
---|
| 616 | *
|
---|
| 617 | * This method returns immediately and runs the image request asynchronously.
|
---|
| 618 | *
|
---|
| 619 | * @return the future of the requested image
|
---|
| 620 | * @since 10714
|
---|
| 621 | */
|
---|
| 622 | public CompletableFuture<ImageIcon> getAsync() {
|
---|
[10731] | 623 | return name.startsWith(HTTP_PROTOCOL) || name.startsWith(WIKI_PROTOCOL)
|
---|
| 624 | ? CompletableFuture.supplyAsync(this::get, IMAGE_FETCHER)
|
---|
| 625 | : CompletableFuture.completedFuture(get());
|
---|
[10714] | 626 | }
|
---|
| 627 |
|
---|
| 628 | /**
|
---|
[5033] | 629 | * Execute the image request.
|
---|
[8095] | 630 | *
|
---|
[5275] | 631 | * @return the requested image or null if the request failed
|
---|
[7693] | 632 | * @since 7693
|
---|
[5033] | 633 | */
|
---|
[7693] | 634 | public ImageResource getResource() {
|
---|
[5033] | 635 | ImageResource ir = getIfAvailableImpl(additionalClassLoaders);
|
---|
[4721] | 636 | if (ir == null) {
|
---|
| 637 | if (!optional) {
|
---|
| 638 | String ext = name.indexOf('.') != -1 ? "" : ".???";
|
---|
[11374] | 639 | throw new JosmRuntimeException(
|
---|
[8509] | 640 | tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.",
|
---|
| 641 | name + ext));
|
---|
[4721] | 642 | } else {
|
---|
[5055] | 643 | if (!suppressWarnings) {
|
---|
[6248] | 644 | Main.error(tr("Failed to locate image ''{0}''", name));
|
---|
[5027] | 645 | }
|
---|
[4721] | 646 | return null;
|
---|
| 647 | }
|
---|
| 648 | }
|
---|
[8095] | 649 | if (overlayInfo != null) {
|
---|
| 650 | ir = new ImageResource(ir, overlayInfo);
|
---|
| 651 | }
|
---|
[10428] | 652 | if (isDisabled) {
|
---|
| 653 | ir.setDisabled(true);
|
---|
| 654 | }
|
---|
[7693] | 655 | return ir;
|
---|
[4721] | 656 | }
|
---|
| 657 |
|
---|
| 658 | /**
|
---|
[5054] | 659 | * Load the image in a background thread.
|
---|
| 660 | *
|
---|
[10616] | 661 | * This method returns immediately and runs the image request asynchronously.
|
---|
[5054] | 662 | *
|
---|
[10714] | 663 | * @return the future of the requested image
|
---|
| 664 | * @since 10714
|
---|
[5054] | 665 | */
|
---|
[10731] | 666 | public CompletableFuture<ImageResource> getResourceAsync() {
|
---|
| 667 | return name.startsWith(HTTP_PROTOCOL) || name.startsWith(WIKI_PROTOCOL)
|
---|
| 668 | ? CompletableFuture.supplyAsync(this::getResource, IMAGE_FETCHER)
|
---|
| 669 | : CompletableFuture.completedFuture(getResource());
|
---|
[5054] | 670 | }
|
---|
| 671 |
|
---|
| 672 | /**
|
---|
[5275] | 673 | * Load an image with a given file name.
|
---|
[2512] | 674 | *
|
---|
[5275] | 675 | * @param subdir subdirectory the image lies in
|
---|
| 676 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
[1169] | 677 | * @return The requested Image.
|
---|
[5275] | 678 | * @throws RuntimeException if the image cannot be located
|
---|
[1169] | 679 | */
|
---|
| 680 | public static ImageIcon get(String subdir, String name) {
|
---|
[4721] | 681 | return new ImageProvider(subdir, name).get();
|
---|
[1169] | 682 | }
|
---|
[200] | 683 |
|
---|
[5275] | 684 | /**
|
---|
[10409] | 685 | * Load an image with a given file name.
|
---|
| 686 | *
|
---|
| 687 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
| 688 | * @return the requested image or null if the request failed
|
---|
| 689 | * @see #get(String, String)
|
---|
| 690 | */
|
---|
| 691 | public static ImageIcon get(String name) {
|
---|
| 692 | return new ImageProvider(name).get();
|
---|
| 693 | }
|
---|
| 694 |
|
---|
| 695 | /**
|
---|
[10428] | 696 | * Load an image from directory with a given file name and size.
|
---|
| 697 | *
|
---|
| 698 | * @param subdir subdirectory the image lies in
|
---|
| 699 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
| 700 | * @param size Target icon size
|
---|
| 701 | * @return The requested Image.
|
---|
| 702 | * @throws RuntimeException if the image cannot be located
|
---|
| 703 | * @since 10428
|
---|
| 704 | */
|
---|
| 705 | public static ImageIcon get(String subdir, String name, ImageSizes size) {
|
---|
| 706 | return new ImageProvider(subdir, name).setSize(size).get();
|
---|
| 707 | }
|
---|
| 708 |
|
---|
| 709 | /**
|
---|
[10358] | 710 | * Load an empty image with a given size.
|
---|
| 711 | *
|
---|
| 712 | * @param size Target icon size
|
---|
| 713 | * @return The requested Image.
|
---|
| 714 | * @since 10358
|
---|
| 715 | */
|
---|
| 716 | public static ImageIcon getEmpty(ImageSizes size) {
|
---|
| 717 | Dimension iconRealSize = GuiSizesHelper.getDimensionDpiAdjusted(size.getImageDimension());
|
---|
| 718 | return new ImageIcon(new BufferedImage(iconRealSize.width, iconRealSize.height,
|
---|
| 719 | BufferedImage.TYPE_INT_ARGB));
|
---|
| 720 | }
|
---|
| 721 |
|
---|
| 722 | /**
|
---|
[5275] | 723 | * Load an image with a given file name, but do not throw an exception
|
---|
| 724 | * when the image cannot be found.
|
---|
[6814] | 725 | *
|
---|
| 726 | * @param subdir subdirectory the image lies in
|
---|
| 727 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
| 728 | * @return the requested image or null if the request failed
|
---|
| 729 | * @see #get(String, String)
|
---|
[5275] | 730 | */
|
---|
[1879] | 731 | public static ImageIcon getIfAvailable(String subdir, String name) {
|
---|
[4721] | 732 | return new ImageProvider(subdir, name).setOptional(true).get();
|
---|
[1169] | 733 | }
|
---|
[1879] | 734 |
|
---|
[1169] | 735 | /**
|
---|
[10428] | 736 | * Load an image with a given file name and size.
|
---|
| 737 | *
|
---|
| 738 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
| 739 | * @param size Target icon size
|
---|
| 740 | * @return the requested image or null if the request failed
|
---|
| 741 | * @see #get(String, String)
|
---|
| 742 | * @since 10428
|
---|
| 743 | */
|
---|
| 744 | public static ImageIcon get(String name, ImageSizes size) {
|
---|
| 745 | return new ImageProvider(name).setSize(size).get();
|
---|
| 746 | }
|
---|
| 747 |
|
---|
| 748 | /**
|
---|
[8095] | 749 | * Load an image with a given file name, but do not throw an exception
|
---|
| 750 | * when the image cannot be found.
|
---|
| 751 | *
|
---|
[6814] | 752 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
| 753 | * @return the requested image or null if the request failed
|
---|
| 754 | * @see #getIfAvailable(String, String)
|
---|
[5275] | 755 | */
|
---|
| 756 | public static ImageIcon getIfAvailable(String name) {
|
---|
| 757 | return new ImageProvider(name).setOptional(true).get();
|
---|
| 758 | }
|
---|
| 759 |
|
---|
| 760 | /**
|
---|
[4713] | 761 | * {@code data:[<mediatype>][;base64],<data>}
|
---|
[5863] | 762 | * @see <a href="http://tools.ietf.org/html/rfc2397">RFC2397</a>
|
---|
[4713] | 763 | */
|
---|
| 764 | private static final Pattern dataUrlPattern = Pattern.compile(
|
---|
| 765 | "^data:([a-zA-Z]+/[a-zA-Z+]+)?(;base64)?,(.+)$");
|
---|
| 766 |
|
---|
[8095] | 767 | /**
|
---|
[11021] | 768 | * Clears the internal image cache.
|
---|
| 769 | * @since 11021
|
---|
| 770 | */
|
---|
| 771 | public static void clearCache() {
|
---|
| 772 | synchronized (cache) {
|
---|
| 773 | cache.clear();
|
---|
| 774 | }
|
---|
| 775 | }
|
---|
| 776 |
|
---|
| 777 | /**
|
---|
[8095] | 778 | * Internal implementation of the image request.
|
---|
| 779 | *
|
---|
| 780 | * @param additionalClassLoaders the list of class loaders to use
|
---|
| 781 | * @return the requested image or null if the request failed
|
---|
| 782 | */
|
---|
[5033] | 783 | private ImageResource getIfAvailableImpl(Collection<ClassLoader> additionalClassLoaders) {
|
---|
[5540] | 784 | synchronized (cache) {
|
---|
| 785 | // This method is called from different thread and modifying HashMap concurrently can result
|
---|
| 786 | // for example in loops in map entries (ie freeze when such entry is retrieved)
|
---|
| 787 | // Yes, it did happen to me :-)
|
---|
| 788 | if (name == null)
|
---|
| 789 | return null;
|
---|
[4713] | 790 |
|
---|
[11649] | 791 | String prefix = isDisabled ? "dis:" : "";
|
---|
[6747] | 792 | if (name.startsWith("data:")) {
|
---|
| 793 | String url = name;
|
---|
[10428] | 794 | ImageResource ir = cache.get(prefix+url);
|
---|
[6747] | 795 | if (ir != null) return ir;
|
---|
| 796 | ir = getIfAvailableDataUrl(url);
|
---|
| 797 | if (ir != null) {
|
---|
[10428] | 798 | cache.put(prefix+url, ir);
|
---|
[4713] | 799 | }
|
---|
[6747] | 800 | return ir;
|
---|
[4713] | 801 | }
|
---|
| 802 |
|
---|
[8404] | 803 | ImageType type = Utils.hasExtension(name, "svg") ? ImageType.SVG : ImageType.OTHER;
|
---|
[4256] | 804 |
|
---|
[7748] | 805 | if (name.startsWith(HTTP_PROTOCOL) || name.startsWith(HTTPS_PROTOCOL)) {
|
---|
[5540] | 806 | String url = name;
|
---|
[10428] | 807 | ImageResource ir = cache.get(prefix+url);
|
---|
[5540] | 808 | if (ir != null) return ir;
|
---|
| 809 | ir = getIfAvailableHttp(url, type);
|
---|
| 810 | if (ir != null) {
|
---|
[10428] | 811 | cache.put(prefix+url, ir);
|
---|
[5540] | 812 | }
|
---|
| 813 | return ir;
|
---|
[7748] | 814 | } else if (name.startsWith(WIKI_PROTOCOL)) {
|
---|
[10428] | 815 | ImageResource ir = cache.get(prefix+name);
|
---|
[5540] | 816 | if (ir != null) return ir;
|
---|
| 817 | ir = getIfAvailableWiki(name, type);
|
---|
| 818 | if (ir != null) {
|
---|
[10428] | 819 | cache.put(prefix+name, ir);
|
---|
[5540] | 820 | }
|
---|
| 821 | return ir;
|
---|
[4256] | 822 | }
|
---|
[5540] | 823 |
|
---|
| 824 | if (subdir == null) {
|
---|
| 825 | subdir = "";
|
---|
[8102] | 826 | } else if (!subdir.isEmpty() && !subdir.endsWith("/")) {
|
---|
[8846] | 827 | subdir += '/';
|
---|
[4403] | 828 | }
|
---|
[5540] | 829 | String[] extensions;
|
---|
| 830 | if (name.indexOf('.') != -1) {
|
---|
[8443] | 831 | extensions = new String[] {""};
|
---|
[5540] | 832 | } else {
|
---|
[8443] | 833 | extensions = new String[] {".png", ".svg"};
|
---|
[5540] | 834 | }
|
---|
[10001] | 835 | final int typeArchive = 0;
|
---|
| 836 | final int typeLocal = 1;
|
---|
| 837 | for (int place : new Integer[] {typeArchive, typeLocal}) {
|
---|
[5540] | 838 | for (String ext : extensions) {
|
---|
[4256] | 839 |
|
---|
[5540] | 840 | if (".svg".equals(ext)) {
|
---|
| 841 | type = ImageType.SVG;
|
---|
| 842 | } else if (".png".equals(ext)) {
|
---|
| 843 | type = ImageType.OTHER;
|
---|
| 844 | }
|
---|
[4261] | 845 |
|
---|
[6987] | 846 | String fullName = subdir + name + ext;
|
---|
[10428] | 847 | String cacheName = prefix + fullName;
|
---|
[5540] | 848 | /* cache separately */
|
---|
[6093] | 849 | if (dirs != null && !dirs.isEmpty()) {
|
---|
[8846] | 850 | cacheName = "id:" + id + ':' + fullName;
|
---|
[8510] | 851 | if (archive != null) {
|
---|
[8846] | 852 | cacheName += ':' + archive.getName();
|
---|
[5540] | 853 | }
|
---|
[4261] | 854 | }
|
---|
[4256] | 855 |
|
---|
[5540] | 856 | switch (place) {
|
---|
[10001] | 857 | case typeArchive:
|
---|
[4261] | 858 | if (archive != null) {
|
---|
[10462] | 859 | cacheName = "zip:"+archive.hashCode()+':'+cacheName;
|
---|
[10403] | 860 | ImageResource ir = cache.get(cacheName);
|
---|
| 861 | if (ir != null) return ir;
|
---|
| 862 |
|
---|
[6987] | 863 | ir = getIfAvailableZip(fullName, archive, inArchiveDir, type);
|
---|
[4271] | 864 | if (ir != null) {
|
---|
[6987] | 865 | cache.put(cacheName, ir);
|
---|
[4271] | 866 | return ir;
|
---|
[4261] | 867 | }
|
---|
| 868 | }
|
---|
| 869 | break;
|
---|
[10001] | 870 | case typeLocal:
|
---|
[10403] | 871 | ImageResource ir = cache.get(cacheName);
|
---|
| 872 | if (ir != null) return ir;
|
---|
| 873 |
|
---|
[4261] | 874 | // getImageUrl() does a ton of "stat()" calls and gets expensive
|
---|
| 875 | // and redundant when you have a whole ton of objects. So,
|
---|
| 876 | // index the cache by the name of the icon we're looking for
|
---|
| 877 | // and don't bother to create a URL unless we're actually
|
---|
| 878 | // creating the image.
|
---|
[6987] | 879 | URL path = getImageUrl(fullName, dirs, additionalClassLoaders);
|
---|
[4403] | 880 | if (path == null) {
|
---|
[4261] | 881 | continue;
|
---|
[4403] | 882 | }
|
---|
[4271] | 883 | ir = getIfAvailableLocalURL(path, type);
|
---|
| 884 | if (ir != null) {
|
---|
[6987] | 885 | cache.put(cacheName, ir);
|
---|
[4271] | 886 | return ir;
|
---|
[4261] | 887 | }
|
---|
| 888 | break;
|
---|
[5540] | 889 | }
|
---|
[4256] | 890 | }
|
---|
[2889] | 891 | }
|
---|
[5540] | 892 | return null;
|
---|
[1169] | 893 | }
|
---|
| 894 | }
|
---|
[293] | 895 |
|
---|
[8095] | 896 | /**
|
---|
| 897 | * Internal implementation of the image request for URL's.
|
---|
| 898 | *
|
---|
| 899 | * @param url URL of the image
|
---|
| 900 | * @param type data type of the image
|
---|
| 901 | * @return the requested image or null if the request failed
|
---|
| 902 | */
|
---|
[4271] | 903 | private static ImageResource getIfAvailableHttp(String url, ImageType type) {
|
---|
[11399] | 904 | try (CachedFile cf = new CachedFile(url).setDestDir(new File(Main.pref.getCacheDirectory(), "images").getPath());
|
---|
| 905 | InputStream is = cf.getInputStream()) {
|
---|
[4256] | 906 | switch (type) {
|
---|
[5540] | 907 | case SVG:
|
---|
[7805] | 908 | SVGDiagram svg = null;
|
---|
| 909 | synchronized (getSvgUniverse()) {
|
---|
| 910 | URI uri = getSvgUniverse().loadSVG(is, Utils.fileToURL(cf.getFile()).toString());
|
---|
| 911 | svg = getSvgUniverse().getDiagram(uri);
|
---|
| 912 | }
|
---|
[5540] | 913 | return svg == null ? null : new ImageResource(svg);
|
---|
| 914 | case OTHER:
|
---|
| 915 | BufferedImage img = null;
|
---|
| 916 | try {
|
---|
[7248] | 917 | img = read(Utils.fileToURL(cf.getFile()), false, false);
|
---|
[6246] | 918 | } catch (IOException e) {
|
---|
[10627] | 919 | Main.warn(e, "IOException while reading HTTP image:");
|
---|
[6246] | 920 | }
|
---|
[5540] | 921 | return img == null ? null : new ImageResource(img);
|
---|
| 922 | default:
|
---|
[11399] | 923 | throw new AssertionError("Unsupported type: " + type);
|
---|
[4255] | 924 | }
|
---|
[4256] | 925 | } catch (IOException e) {
|
---|
[10627] | 926 | Main.debug(e);
|
---|
[4271] | 927 | return null;
|
---|
[4255] | 928 | }
|
---|
| 929 | }
|
---|
| 930 |
|
---|
[8095] | 931 | /**
|
---|
| 932 | * Internal implementation of the image request for inline images (<b>data:</b> urls).
|
---|
| 933 | *
|
---|
| 934 | * @param url the data URL for image extraction
|
---|
| 935 | * @return the requested image or null if the request failed
|
---|
| 936 | */
|
---|
[6747] | 937 | private static ImageResource getIfAvailableDataUrl(String url) {
|
---|
[8304] | 938 | Matcher m = dataUrlPattern.matcher(url);
|
---|
| 939 | if (m.matches()) {
|
---|
| 940 | String base64 = m.group(2);
|
---|
| 941 | String data = m.group(3);
|
---|
| 942 | byte[] bytes;
|
---|
| 943 | if (";base64".equals(base64)) {
|
---|
[10746] | 944 | bytes = Base64.getDecoder().decode(data);
|
---|
[8304] | 945 | } else {
|
---|
| 946 | try {
|
---|
| 947 | bytes = Utils.decodeUrl(data).getBytes(StandardCharsets.UTF_8);
|
---|
| 948 | } catch (IllegalArgumentException ex) {
|
---|
[10627] | 949 | Main.warn(ex, "Unable to decode URL data part: "+ex.getMessage() + " (" + data + ')');
|
---|
[8304] | 950 | return null;
|
---|
[6809] | 951 | }
|
---|
[8304] | 952 | }
|
---|
[9062] | 953 | String mediatype = m.group(1);
|
---|
[8304] | 954 | if ("image/svg+xml".equals(mediatype)) {
|
---|
| 955 | String s = new String(bytes, StandardCharsets.UTF_8);
|
---|
[10308] | 956 | SVGDiagram svg;
|
---|
[8304] | 957 | synchronized (getSvgUniverse()) {
|
---|
| 958 | URI uri = getSvgUniverse().loadSVG(new StringReader(s), Utils.encodeUrl(s));
|
---|
| 959 | svg = getSvgUniverse().getDiagram(uri);
|
---|
[6747] | 960 | }
|
---|
[8304] | 961 | if (svg == null) {
|
---|
| 962 | Main.warn("Unable to process svg: "+s);
|
---|
| 963 | return null;
|
---|
| 964 | }
|
---|
| 965 | return new ImageResource(svg);
|
---|
| 966 | } else {
|
---|
| 967 | try {
|
---|
| 968 | // See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
|
---|
| 969 | // This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
|
---|
[8540] | 970 | // CHECKSTYLE.OFF: LineLength
|
---|
[10580] | 971 | // hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/dc4322602480/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
|
---|
[8540] | 972 | // CHECKSTYLE.ON: LineLength
|
---|
[8304] | 973 | Image img = read(new ByteArrayInputStream(bytes), false, true);
|
---|
| 974 | return img == null ? null : new ImageResource(img);
|
---|
| 975 | } catch (IOException e) {
|
---|
[10627] | 976 | Main.warn(e, "IOException while reading image:");
|
---|
[8304] | 977 | }
|
---|
[6747] | 978 | }
|
---|
| 979 | }
|
---|
[8304] | 980 | return null;
|
---|
[6747] | 981 | }
|
---|
| 982 |
|
---|
[8095] | 983 | /**
|
---|
| 984 | * Internal implementation of the image request for wiki images.
|
---|
| 985 | *
|
---|
| 986 | * @param name image file name
|
---|
| 987 | * @param type data type of the image
|
---|
| 988 | * @return the requested image or null if the request failed
|
---|
| 989 | */
|
---|
[4403] | 990 | private static ImageResource getIfAvailableWiki(String name, ImageType type) {
|
---|
| 991 | final Collection<String> defaultBaseUrls = Arrays.asList(
|
---|
[9147] | 992 | "https://wiki.openstreetmap.org/w/images/",
|
---|
| 993 | "https://upload.wikimedia.org/wikipedia/commons/",
|
---|
| 994 | "https://wiki.openstreetmap.org/wiki/File:"
|
---|
[5540] | 995 | );
|
---|
[4403] | 996 | final Collection<String> baseUrls = Main.pref.getCollection("image-provider.wiki.urls", defaultBaseUrls);
|
---|
| 997 |
|
---|
| 998 | final String fn = name.substring(name.lastIndexOf('/') + 1);
|
---|
| 999 |
|
---|
| 1000 | ImageResource result = null;
|
---|
| 1001 | for (String b : baseUrls) {
|
---|
| 1002 | String url;
|
---|
| 1003 | if (b.endsWith(":")) {
|
---|
| 1004 | url = getImgUrlFromWikiInfoPage(b, fn);
|
---|
| 1005 | if (url == null) {
|
---|
| 1006 | continue;
|
---|
| 1007 | }
|
---|
| 1008 | } else {
|
---|
[10001] | 1009 | final String fnMD5 = Utils.md5Hex(fn);
|
---|
[10300] | 1010 | url = b + fnMD5.substring(0, 1) + '/' + fnMD5.substring(0, 2) + '/' + fn;
|
---|
[4403] | 1011 | }
|
---|
| 1012 | result = getIfAvailableHttp(url, type);
|
---|
| 1013 | if (result != null) {
|
---|
| 1014 | break;
|
---|
| 1015 | }
|
---|
| 1016 | }
|
---|
| 1017 | return result;
|
---|
| 1018 | }
|
---|
| 1019 |
|
---|
[8095] | 1020 | /**
|
---|
| 1021 | * Internal implementation of the image request for images in Zip archives.
|
---|
| 1022 | *
|
---|
| 1023 | * @param fullName image file name
|
---|
| 1024 | * @param archive the archive to get image from
|
---|
| 1025 | * @param inArchiveDir directory of the image inside the archive or <code>null</code>
|
---|
| 1026 | * @param type data type of the image
|
---|
| 1027 | * @return the requested image or null if the request failed
|
---|
| 1028 | */
|
---|
[6987] | 1029 | private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
|
---|
[7089] | 1030 | try (ZipFile zipFile = new ZipFile(archive, StandardCharsets.UTF_8)) {
|
---|
[7012] | 1031 | if (inArchiveDir == null || ".".equals(inArchiveDir)) {
|
---|
[6151] | 1032 | inArchiveDir = "";
|
---|
| 1033 | } else if (!inArchiveDir.isEmpty()) {
|
---|
[8846] | 1034 | inArchiveDir += '/';
|
---|
[6148] | 1035 | }
|
---|
[6987] | 1036 | String entryName = inArchiveDir + fullName;
|
---|
| 1037 | ZipEntry entry = zipFile.getEntry(entryName);
|
---|
[7033] | 1038 | if (entry != null) {
|
---|
[8510] | 1039 | int size = (int) entry.getSize();
|
---|
[4255] | 1040 | int offs = 0;
|
---|
| 1041 | byte[] buf = new byte[size];
|
---|
[7033] | 1042 | try (InputStream is = zipFile.getInputStream(entry)) {
|
---|
[4256] | 1043 | switch (type) {
|
---|
[5540] | 1044 | case SVG:
|
---|
[7805] | 1045 | SVGDiagram svg = null;
|
---|
| 1046 | synchronized (getSvgUniverse()) {
|
---|
| 1047 | URI uri = getSvgUniverse().loadSVG(is, entryName);
|
---|
| 1048 | svg = getSvgUniverse().getDiagram(uri);
|
---|
| 1049 | }
|
---|
[5540] | 1050 | return svg == null ? null : new ImageResource(svg);
|
---|
| 1051 | case OTHER:
|
---|
[8510] | 1052 | while (size > 0) {
|
---|
[5540] | 1053 | int l = is.read(buf, offs, size);
|
---|
| 1054 | offs += l;
|
---|
| 1055 | size -= l;
|
---|
| 1056 | }
|
---|
| 1057 | BufferedImage img = null;
|
---|
| 1058 | try {
|
---|
[7132] | 1059 | img = read(new ByteArrayInputStream(buf), false, false);
|
---|
[6310] | 1060 | } catch (IOException e) {
|
---|
| 1061 | Main.warn(e);
|
---|
| 1062 | }
|
---|
[5540] | 1063 | return img == null ? null : new ImageResource(img);
|
---|
| 1064 | default:
|
---|
[7033] | 1065 | throw new AssertionError("Unknown ImageType: "+type);
|
---|
[4255] | 1066 | }
|
---|
| 1067 | }
|
---|
| 1068 | }
|
---|
[10212] | 1069 | } catch (IOException e) {
|
---|
[10627] | 1070 | Main.warn(e, tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
|
---|
[4255] | 1071 | }
|
---|
[4271] | 1072 | return null;
|
---|
[4255] | 1073 | }
|
---|
| 1074 |
|
---|
[8095] | 1075 | /**
|
---|
| 1076 | * Internal implementation of the image request for local images.
|
---|
| 1077 | *
|
---|
| 1078 | * @param path image file path
|
---|
| 1079 | * @param type data type of the image
|
---|
| 1080 | * @return the requested image or null if the request failed
|
---|
| 1081 | */
|
---|
[4271] | 1082 | private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
|
---|
[4256] | 1083 | switch (type) {
|
---|
[5540] | 1084 | case SVG:
|
---|
[10308] | 1085 | SVGDiagram svg;
|
---|
[7805] | 1086 | synchronized (getSvgUniverse()) {
|
---|
| 1087 | URI uri = getSvgUniverse().loadSVG(path);
|
---|
| 1088 | svg = getSvgUniverse().getDiagram(uri);
|
---|
| 1089 | }
|
---|
[5540] | 1090 | return svg == null ? null : new ImageResource(svg);
|
---|
| 1091 | case OTHER:
|
---|
| 1092 | BufferedImage img = null;
|
---|
| 1093 | try {
|
---|
[7495] | 1094 | // See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
|
---|
| 1095 | // This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
|
---|
[10580] | 1096 | // hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/dc4322602480/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
|
---|
[7495] | 1097 | img = read(path, false, true);
|
---|
| 1098 | if (Main.isDebugEnabled() && isTransparencyForced(img)) {
|
---|
| 1099 | Main.debug("Transparency has been forced for image "+path.toExternalForm());
|
---|
| 1100 | }
|
---|
[6283] | 1101 | } catch (IOException e) {
|
---|
| 1102 | Main.warn(e);
|
---|
| 1103 | }
|
---|
[5540] | 1104 | return img == null ? null : new ImageResource(img);
|
---|
| 1105 | default:
|
---|
| 1106 | throw new AssertionError();
|
---|
[4256] | 1107 | }
|
---|
| 1108 | }
|
---|
| 1109 |
|
---|
[5033] | 1110 | private static URL getImageUrl(String path, String name, Collection<ClassLoader> additionalClassLoaders) {
|
---|
[4256] | 1111 | if (path != null && path.startsWith("resource://")) {
|
---|
[1169] | 1112 | String p = path.substring("resource://".length());
|
---|
[7005] | 1113 | Collection<ClassLoader> classLoaders = new ArrayList<>(PluginHandler.getResourceClassLoaders());
|
---|
[5033] | 1114 | if (additionalClassLoaders != null) {
|
---|
| 1115 | classLoaders.addAll(additionalClassLoaders);
|
---|
| 1116 | }
|
---|
| 1117 | for (ClassLoader source : classLoaders) {
|
---|
[1169] | 1118 | URL res;
|
---|
[1879] | 1119 | if ((res = source.getResource(p + name)) != null)
|
---|
[1169] | 1120 | return res;
|
---|
| 1121 | }
|
---|
[1879] | 1122 | } else {
|
---|
[6615] | 1123 | File f = new File(path, name);
|
---|
| 1124 | if ((path != null || f.isAbsolute()) && f.exists())
|
---|
| 1125 | return Utils.fileToURL(f);
|
---|
[1169] | 1126 | }
|
---|
| 1127 | return null;
|
---|
| 1128 | }
|
---|
[293] | 1129 |
|
---|
[5033] | 1130 | private static URL getImageUrl(String imageName, Collection<String> dirs, Collection<ClassLoader> additionalClassLoaders) {
|
---|
[10308] | 1131 | URL u;
|
---|
[1879] | 1132 |
|
---|
[1169] | 1133 | // Try passed directories first
|
---|
[1879] | 1134 | if (dirs != null) {
|
---|
| 1135 | for (String name : dirs) {
|
---|
| 1136 | try {
|
---|
[5033] | 1137 | u = getImageUrl(name, imageName, additionalClassLoaders);
|
---|
[1879] | 1138 | if (u != null)
|
---|
| 1139 | return u;
|
---|
| 1140 | } catch (SecurityException e) {
|
---|
[10627] | 1141 | Main.warn(e, tr(
|
---|
[6248] | 1142 | "Failed to access directory ''{0}'' for security reasons. Exception was: {1}",
|
---|
[1879] | 1143 | name, e.toString()));
|
---|
| 1144 | }
|
---|
| 1145 |
|
---|
[1169] | 1146 | }
|
---|
| 1147 | }
|
---|
[7834] | 1148 | // Try user-data directory
|
---|
[9454] | 1149 | if (Main.pref != null) {
|
---|
| 1150 | String dir = new File(Main.pref.getUserDataDirectory(), "images").getAbsolutePath();
|
---|
| 1151 | try {
|
---|
| 1152 | u = getImageUrl(dir, imageName, additionalClassLoaders);
|
---|
| 1153 | if (u != null)
|
---|
| 1154 | return u;
|
---|
| 1155 | } catch (SecurityException e) {
|
---|
[10627] | 1156 | Main.warn(e, tr(
|
---|
[9454] | 1157 | "Failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
|
---|
| 1158 | .toString()));
|
---|
| 1159 | }
|
---|
[1879] | 1160 | }
|
---|
[243] | 1161 |
|
---|
[4256] | 1162 | // Absolute path?
|
---|
[5033] | 1163 | u = getImageUrl(null, imageName, additionalClassLoaders);
|
---|
[4256] | 1164 | if (u != null)
|
---|
| 1165 | return u;
|
---|
| 1166 |
|
---|
[1169] | 1167 | // Try plugins and josm classloader
|
---|
[5033] | 1168 | u = getImageUrl("resource://images/", imageName, additionalClassLoaders);
|
---|
[1879] | 1169 | if (u != null)
|
---|
| 1170 | return u;
|
---|
[991] | 1171 |
|
---|
[2927] | 1172 | // Try all other resource directories
|
---|
[9454] | 1173 | if (Main.pref != null) {
|
---|
| 1174 | for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
|
---|
| 1175 | u = getImageUrl(location + "images", imageName, additionalClassLoaders);
|
---|
| 1176 | if (u != null)
|
---|
| 1177 | return u;
|
---|
| 1178 | u = getImageUrl(location, imageName, additionalClassLoaders);
|
---|
| 1179 | if (u != null)
|
---|
| 1180 | return u;
|
---|
| 1181 | }
|
---|
[1169] | 1182 | }
|
---|
[4256] | 1183 |
|
---|
[1169] | 1184 | return null;
|
---|
| 1185 | }
|
---|
[17] | 1186 |
|
---|
[7090] | 1187 | /** Quit parsing, when a certain condition is met */
|
---|
| 1188 | private static class SAXReturnException extends SAXException {
|
---|
| 1189 | private final String result;
|
---|
| 1190 |
|
---|
[8836] | 1191 | SAXReturnException(String result) {
|
---|
[7090] | 1192 | this.result = result;
|
---|
| 1193 | }
|
---|
| 1194 |
|
---|
| 1195 | public String getResult() {
|
---|
| 1196 | return result;
|
---|
| 1197 | }
|
---|
| 1198 | }
|
---|
| 1199 |
|
---|
[4403] | 1200 | /**
|
---|
[8096] | 1201 | * Reads the wiki page on a certain file in html format in order to find the real image URL.
|
---|
[8095] | 1202 | *
|
---|
| 1203 | * @param base base URL for Wiki image
|
---|
| 1204 | * @param fn filename of the Wiki image
|
---|
| 1205 | * @return image URL for a Wiki image or null in case of error
|
---|
[4403] | 1206 | */
|
---|
| 1207 | private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
|
---|
| 1208 | try {
|
---|
[10741] | 1209 | final XMLReader parser = Utils.newSafeSAXParser().getXMLReader();
|
---|
[4403] | 1210 | parser.setContentHandler(new DefaultHandler() {
|
---|
| 1211 | @Override
|
---|
| 1212 | public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
|
---|
[7025] | 1213 | if ("img".equalsIgnoreCase(localName)) {
|
---|
[4403] | 1214 | String val = atts.getValue("src");
|
---|
| 1215 | if (val.endsWith(fn))
|
---|
| 1216 | throw new SAXReturnException(val); // parsing done, quit early
|
---|
| 1217 | }
|
---|
| 1218 | }
|
---|
| 1219 | });
|
---|
| 1220 |
|
---|
[10616] | 1221 | parser.setEntityResolver((publicId, systemId) -> new InputSource(new ByteArrayInputStream(new byte[0])));
|
---|
[4403] | 1222 |
|
---|
[11399] | 1223 | try (CachedFile cf = new CachedFile(base + fn).setDestDir(new File(Main.pref.getUserDataDirectory(), "images").getPath());
|
---|
| 1224 | InputStream is = cf.getInputStream()) {
|
---|
[7033] | 1225 | parser.parse(new InputSource(is));
|
---|
| 1226 | }
|
---|
[11620] | 1227 | } catch (SAXReturnException e) {
|
---|
| 1228 | Main.trace(e);
|
---|
| 1229 | return e.getResult();
|
---|
[10741] | 1230 | } catch (IOException | SAXException | ParserConfigurationException e) {
|
---|
[6248] | 1231 | Main.warn("Parsing " + base + fn + " failed:\n" + e);
|
---|
[4403] | 1232 | return null;
|
---|
| 1233 | }
|
---|
[6248] | 1234 | Main.warn("Parsing " + base + fn + " failed: Unexpected content.");
|
---|
[4403] | 1235 | return null;
|
---|
| 1236 | }
|
---|
| 1237 |
|
---|
[7731] | 1238 | /**
|
---|
| 1239 | * Load a cursor with a given file name, optionally decorated with an overlay image.
|
---|
| 1240 | *
|
---|
| 1241 | * @param name the cursor image filename in "cursor" directory
|
---|
| 1242 | * @param overlay optional overlay image
|
---|
| 1243 | * @return cursor with a given file name, optionally decorated with an overlay image
|
---|
| 1244 | */
|
---|
[1169] | 1245 | public static Cursor getCursor(String name, String overlay) {
|
---|
[1879] | 1246 | ImageIcon img = get("cursor", name);
|
---|
[1814] | 1247 | if (overlay != null) {
|
---|
[8095] | 1248 | img = new ImageProvider("cursor", name).setMaxSize(ImageSizes.CURSOR)
|
---|
| 1249 | .addOverlay(new ImageOverlay(new ImageProvider("cursor/modifier/" + overlay)
|
---|
| 1250 | .setMaxSize(ImageSizes.CURSOROVERLAY))).get();
|
---|
[1814] | 1251 | }
|
---|
[7075] | 1252 | if (GraphicsEnvironment.isHeadless()) {
|
---|
[8992] | 1253 | if (Main.isDebugEnabled()) {
|
---|
| 1254 | Main.debug("Cursors are not available in headless mode. Returning null for '"+name+'\'');
|
---|
| 1255 | }
|
---|
[7075] | 1256 | return null;
|
---|
| 1257 | }
|
---|
[7024] | 1258 | return Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
|
---|
[7012] | 1259 | "crosshair".equals(name) ? new Point(10, 10) : new Point(3, 2), "Cursor");
|
---|
[1169] | 1260 | }
|
---|
[159] | 1261 |
|
---|
[5275] | 1262 | /** 90 degrees in radians units */
|
---|
[8285] | 1263 | private static final double DEGREE_90 = 90.0 * Math.PI / 180.0;
|
---|
[1295] | 1264 |
|
---|
| 1265 | /**
|
---|
| 1266 | * Creates a rotated version of the input image.
|
---|
[2512] | 1267 | *
|
---|
[5275] | 1268 | * @param img the image to be rotated.
|
---|
[1295] | 1269 | * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
|
---|
[6814] | 1270 | * will mod it with 360 before using it. More over for caching performance, it will be rounded to
|
---|
[6172] | 1271 | * an entire value between 0 and 360.
|
---|
[2512] | 1272 | *
|
---|
[1295] | 1273 | * @return the image after rotating.
|
---|
[6172] | 1274 | * @since 6172
|
---|
[1295] | 1275 | */
|
---|
[6172] | 1276 | public static Image createRotatedImage(Image img, double rotatedAngle) {
|
---|
| 1277 | return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
|
---|
| 1278 | }
|
---|
[6814] | 1279 |
|
---|
[6172] | 1280 | /**
|
---|
| 1281 | * Creates a rotated version of the input image, scaled to the given dimension.
|
---|
| 1282 | *
|
---|
| 1283 | * @param img the image to be rotated.
|
---|
| 1284 | * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
|
---|
[6814] | 1285 | * will mod it with 360 before using it. More over for caching performance, it will be rounded to
|
---|
[6172] | 1286 | * an entire value between 0 and 360.
|
---|
| 1287 | * @param dimension The requested dimensions. Use (-1,-1) for the original size
|
---|
| 1288 | * and (width, -1) to set the width, but otherwise scale the image proportionally.
|
---|
| 1289 | * @return the image after rotating and scaling.
|
---|
| 1290 | * @since 6172
|
---|
| 1291 | */
|
---|
| 1292 | public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
|
---|
| 1293 | CheckParameterUtil.ensureParameterNotNull(img, "img");
|
---|
[6814] | 1294 |
|
---|
[6172] | 1295 | // convert rotatedAngle to an integer value from 0 to 360
|
---|
| 1296 | Long originalAngle = Math.round(rotatedAngle % 360);
|
---|
[8393] | 1297 | if (rotatedAngle != 0 && originalAngle == 0) {
|
---|
[6172] | 1298 | originalAngle = 360L;
|
---|
[1295] | 1299 | }
|
---|
[6814] | 1300 |
|
---|
[10308] | 1301 | ImageResource imageResource;
|
---|
[1295] | 1302 |
|
---|
[6235] | 1303 | synchronized (ROTATE_CACHE) {
|
---|
| 1304 | Map<Long, ImageResource> cacheByAngle = ROTATE_CACHE.get(img);
|
---|
[6172] | 1305 | if (cacheByAngle == null) {
|
---|
[10179] | 1306 | cacheByAngle = new HashMap<>();
|
---|
| 1307 | ROTATE_CACHE.put(img, cacheByAngle);
|
---|
[6172] | 1308 | }
|
---|
[6814] | 1309 |
|
---|
[6172] | 1310 | imageResource = cacheByAngle.get(originalAngle);
|
---|
[6814] | 1311 |
|
---|
[6172] | 1312 | if (imageResource == null) {
|
---|
| 1313 | // convert originalAngle to a value from 0 to 90
|
---|
| 1314 | double angle = originalAngle % 90;
|
---|
[8393] | 1315 | if (originalAngle != 0 && angle == 0) {
|
---|
[6172] | 1316 | angle = 90.0;
|
---|
| 1317 | }
|
---|
[6814] | 1318 |
|
---|
[12131] | 1319 | double radian = Utils.toRadians(angle);
|
---|
[6814] | 1320 |
|
---|
[6172] | 1321 | new ImageIcon(img); // load completely
|
---|
| 1322 | int iw = img.getWidth(null);
|
---|
| 1323 | int ih = img.getHeight(null);
|
---|
| 1324 | int w;
|
---|
| 1325 | int h;
|
---|
[6814] | 1326 |
|
---|
[6172] | 1327 | if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
|
---|
| 1328 | w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
|
---|
| 1329 | h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
|
---|
| 1330 | } else {
|
---|
| 1331 | w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
|
---|
| 1332 | h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
|
---|
| 1333 | }
|
---|
| 1334 | Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
---|
[10179] | 1335 | imageResource = new ImageResource(image);
|
---|
| 1336 | cacheByAngle.put(originalAngle, imageResource);
|
---|
[6172] | 1337 | Graphics g = image.getGraphics();
|
---|
| 1338 | Graphics2D g2d = (Graphics2D) g.create();
|
---|
[6814] | 1339 |
|
---|
[6172] | 1340 | // calculate the center of the icon.
|
---|
| 1341 | int cx = iw / 2;
|
---|
| 1342 | int cy = ih / 2;
|
---|
[6814] | 1343 |
|
---|
[6172] | 1344 | // move the graphics center point to the center of the icon.
|
---|
| 1345 | g2d.translate(w / 2, h / 2);
|
---|
[6814] | 1346 |
|
---|
[6172] | 1347 | // rotate the graphics about the center point of the icon
|
---|
[12131] | 1348 | g2d.rotate(Utils.toRadians(originalAngle));
|
---|
[6814] | 1349 |
|
---|
[6172] | 1350 | g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
---|
| 1351 | g2d.drawImage(img, -cx, -cy, null);
|
---|
[6814] | 1352 |
|
---|
[6172] | 1353 | g2d.dispose();
|
---|
| 1354 | new ImageIcon(image); // load completely
|
---|
| 1355 | }
|
---|
| 1356 | return imageResource.getImageIcon(dimension).getImage();
|
---|
[1295] | 1357 | }
|
---|
| 1358 | }
|
---|
[6814] | 1359 |
|
---|
[6172] | 1360 | /**
|
---|
| 1361 | * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
|
---|
| 1362 | *
|
---|
| 1363 | * @param img the image to be scaled down.
|
---|
[6814] | 1364 | * @param maxSize the maximum size in pixels (both for width and height)
|
---|
[6172] | 1365 | *
|
---|
| 1366 | * @return the image after scaling.
|
---|
| 1367 | * @since 6172
|
---|
| 1368 | */
|
---|
| 1369 | public static Image createBoundedImage(Image img, int maxSize) {
|
---|
| 1370 | return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
|
---|
| 1371 | }
|
---|
[1814] | 1372 |
|
---|
| 1373 | /**
|
---|
| 1374 | * Replies the icon for an OSM primitive type
|
---|
| 1375 | * @param type the type
|
---|
| 1376 | * @return the icon
|
---|
| 1377 | */
|
---|
[5275] | 1378 | public static ImageIcon get(OsmPrimitiveType type) {
|
---|
[2853] | 1379 | CheckParameterUtil.ensureParameterNotNull(type, "type");
|
---|
[1879] | 1380 | return get("data", type.getAPIName());
|
---|
[1814] | 1381 | }
|
---|
[3862] | 1382 |
|
---|
[7731] | 1383 | /**
|
---|
[8903] | 1384 | * @param primitive Object for which an icon shall be fetched. The icon is chosen based on tags.
|
---|
| 1385 | * @param iconSize Target size of icon. Icon is padded if required.
|
---|
| 1386 | * @return Icon for {@code primitive} that fits in cell.
|
---|
| 1387 | * @since 8903
|
---|
| 1388 | */
|
---|
[9705] | 1389 | public static ImageIcon getPadded(OsmPrimitive primitive, Dimension iconSize) {
|
---|
[8903] | 1390 | // Check if the current styles have special icon for tagged nodes.
|
---|
| 1391 | if (primitive instanceof org.openstreetmap.josm.data.osm.Node) {
|
---|
[10140] | 1392 | Pair<StyleElementList, Range> nodeStyles;
|
---|
| 1393 | DataSet ds = primitive.getDataSet();
|
---|
| 1394 | if (ds != null) {
|
---|
| 1395 | ds.getReadLock().lock();
|
---|
| 1396 | }
|
---|
| 1397 | try {
|
---|
| 1398 | nodeStyles = MapPaintStyles.getStyles().generateStyles(primitive, 100, false);
|
---|
| 1399 | } finally {
|
---|
| 1400 | if (ds != null) {
|
---|
| 1401 | ds.getReadLock().unlock();
|
---|
| 1402 | }
|
---|
| 1403 | }
|
---|
[9278] | 1404 | for (StyleElement style : nodeStyles.a) {
|
---|
| 1405 | if (style instanceof NodeElement) {
|
---|
| 1406 | NodeElement nodeStyle = (NodeElement) style;
|
---|
[8903] | 1407 | MapImage icon = nodeStyle.mapImage;
|
---|
| 1408 | if (icon != null) {
|
---|
[10358] | 1409 | int backgroundRealWidth = GuiSizesHelper.getSizeDpiAdjusted(iconSize.width);
|
---|
| 1410 | int backgroundRealHeight = GuiSizesHelper.getSizeDpiAdjusted(iconSize.height);
|
---|
| 1411 | int iconRealWidth = icon.getWidth();
|
---|
| 1412 | int iconRealHeight = icon.getHeight();
|
---|
| 1413 | BufferedImage image = new BufferedImage(backgroundRealWidth, backgroundRealHeight,
|
---|
[8903] | 1414 | BufferedImage.TYPE_INT_ARGB);
|
---|
[10358] | 1415 | double scaleFactor = Math.min(backgroundRealWidth / (double) iconRealWidth, backgroundRealHeight
|
---|
| 1416 | / (double) iconRealHeight);
|
---|
[8903] | 1417 | BufferedImage iconImage = icon.getImage(false);
|
---|
| 1418 | Image scaledIcon;
|
---|
| 1419 | final int scaledWidth;
|
---|
| 1420 | final int scaledHeight;
|
---|
| 1421 | if (scaleFactor < 1) {
|
---|
| 1422 | // Scale icon such that it fits on background.
|
---|
[10358] | 1423 | scaledWidth = (int) (iconRealWidth * scaleFactor);
|
---|
| 1424 | scaledHeight = (int) (iconRealHeight * scaleFactor);
|
---|
[8903] | 1425 | scaledIcon = iconImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);
|
---|
| 1426 | } else {
|
---|
| 1427 | // Use original size, don't upscale.
|
---|
[10358] | 1428 | scaledWidth = iconRealWidth;
|
---|
| 1429 | scaledHeight = iconRealHeight;
|
---|
[8903] | 1430 | scaledIcon = iconImage;
|
---|
| 1431 | }
|
---|
[10358] | 1432 | image.getGraphics().drawImage(scaledIcon, (backgroundRealWidth - scaledWidth) / 2,
|
---|
| 1433 | (backgroundRealHeight - scaledHeight) / 2, null);
|
---|
[8903] | 1434 |
|
---|
| 1435 | return new ImageIcon(image);
|
---|
| 1436 | }
|
---|
| 1437 | }
|
---|
| 1438 | }
|
---|
| 1439 | }
|
---|
| 1440 |
|
---|
[9265] | 1441 | // Check if the presets have icons for nodes/relations.
|
---|
| 1442 | if (!OsmPrimitiveType.WAY.equals(primitive.getType())) {
|
---|
[10616] | 1443 | final Collection<TaggingPreset> presets = new TreeSet<>((o1, o2) -> {
|
---|
| 1444 | final int o1TypesSize = o1.types == null || o1.types.isEmpty() ? Integer.MAX_VALUE : o1.types.size();
|
---|
| 1445 | final int o2TypesSize = o2.types == null || o2.types.isEmpty() ? Integer.MAX_VALUE : o2.types.size();
|
---|
| 1446 | return Integer.compare(o1TypesSize, o2TypesSize);
|
---|
[9691] | 1447 | });
|
---|
| 1448 | presets.addAll(TaggingPresets.getMatchingPresets(primitive));
|
---|
| 1449 | for (final TaggingPreset preset : presets) {
|
---|
[9265] | 1450 | if (preset.getIcon() != null) {
|
---|
| 1451 | return preset.getIcon();
|
---|
| 1452 | }
|
---|
| 1453 | }
|
---|
| 1454 | }
|
---|
| 1455 |
|
---|
[8903] | 1456 | // Use generic default icon.
|
---|
| 1457 | return ImageProvider.get(primitive.getDisplayType());
|
---|
| 1458 | }
|
---|
| 1459 |
|
---|
| 1460 | /**
|
---|
[7731] | 1461 | * Constructs an image from the given SVG data.
|
---|
| 1462 | * @param svg the SVG data
|
---|
| 1463 | * @param dim the desired image dimension
|
---|
| 1464 | * @return an image from the given SVG data at the desired dimension.
|
---|
| 1465 | */
|
---|
[4961] | 1466 | public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
|
---|
[10768] | 1467 | if (Main.isTraceEnabled()) {
|
---|
| 1468 | Main.trace(String.format("createImageFromSvg: %s %s", svg.getXMLBase(), dim));
|
---|
| 1469 | }
|
---|
[10358] | 1470 | float sourceWidth = svg.getWidth();
|
---|
| 1471 | float sourceHeight = svg.getHeight();
|
---|
| 1472 | int realWidth = Math.round(GuiSizesHelper.getSizeDpiAdjusted(sourceWidth));
|
---|
| 1473 | int realHeight = Math.round(GuiSizesHelper.getSizeDpiAdjusted(sourceHeight));
|
---|
| 1474 | Double scaleX, scaleY;
|
---|
[4271] | 1475 | if (dim.width != -1) {
|
---|
[10358] | 1476 | realWidth = dim.width;
|
---|
| 1477 | scaleX = (double) realWidth / sourceWidth;
|
---|
[4271] | 1478 | if (dim.height == -1) {
|
---|
| 1479 | scaleY = scaleX;
|
---|
[10358] | 1480 | realHeight = (int) Math.round(sourceHeight * scaleY);
|
---|
[4271] | 1481 | } else {
|
---|
[10358] | 1482 | realHeight = dim.height;
|
---|
| 1483 | scaleY = (double) realHeight / sourceHeight;
|
---|
[4271] | 1484 | }
|
---|
| 1485 | } else if (dim.height != -1) {
|
---|
[10358] | 1486 | realHeight = dim.height;
|
---|
| 1487 | scaleX = scaleY = (double) realHeight / sourceHeight;
|
---|
| 1488 | realWidth = (int) Math.round(sourceWidth * scaleX);
|
---|
[10362] | 1489 | } else {
|
---|
[10358] | 1490 | scaleX = scaleY = (double) realHeight / sourceHeight;
|
---|
| 1491 | }
|
---|
| 1492 |
|
---|
| 1493 | if (realWidth == 0 || realHeight == 0) {
|
---|
[5830] | 1494 | return null;
|
---|
| 1495 | }
|
---|
[10358] | 1496 | BufferedImage img = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_INT_ARGB);
|
---|
[4961] | 1497 | Graphics2D g = img.createGraphics();
|
---|
[10358] | 1498 | g.setClip(0, 0, realWidth, realHeight);
|
---|
| 1499 | g.scale(scaleX, scaleY);
|
---|
[4256] | 1500 | g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
---|
| 1501 | try {
|
---|
[7804] | 1502 | synchronized (getSvgUniverse()) {
|
---|
| 1503 | svg.render(g);
|
---|
| 1504 | }
|
---|
[10212] | 1505 | } catch (SVGException ex) {
|
---|
[10627] | 1506 | Main.error(ex, "Unable to load svg:");
|
---|
[4256] | 1507 | return null;
|
---|
| 1508 | }
|
---|
| 1509 | return img;
|
---|
| 1510 | }
|
---|
| 1511 |
|
---|
[8126] | 1512 | private static synchronized SVGUniverse getSvgUniverse() {
|
---|
[4256] | 1513 | if (svgUniverse == null) {
|
---|
| 1514 | svgUniverse = new SVGUniverse();
|
---|
| 1515 | }
|
---|
| 1516 | return svgUniverse;
|
---|
| 1517 | }
|
---|
[7132] | 1518 |
|
---|
| 1519 | /**
|
---|
| 1520 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
| 1521 | * a supplied <code>File</code> with an <code>ImageReader</code>
|
---|
| 1522 | * chosen automatically from among those currently registered.
|
---|
| 1523 | * The <code>File</code> is wrapped in an
|
---|
| 1524 | * <code>ImageInputStream</code>. If no registered
|
---|
| 1525 | * <code>ImageReader</code> claims to be able to read the
|
---|
| 1526 | * resulting stream, <code>null</code> is returned.
|
---|
| 1527 | *
|
---|
| 1528 | * <p> The current cache settings from <code>getUseCache</code>and
|
---|
| 1529 | * <code>getCacheDirectory</code> will be used to control caching in the
|
---|
| 1530 | * <code>ImageInputStream</code> that is created.
|
---|
| 1531 | *
|
---|
| 1532 | * <p> Note that there is no <code>read</code> method that takes a
|
---|
| 1533 | * filename as a <code>String</code>; use this method instead after
|
---|
| 1534 | * creating a <code>File</code> from the filename.
|
---|
| 1535 | *
|
---|
| 1536 | * <p> This method does not attempt to locate
|
---|
| 1537 | * <code>ImageReader</code>s that can read directly from a
|
---|
| 1538 | * <code>File</code>; that may be accomplished using
|
---|
| 1539 | * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
|
---|
| 1540 | *
|
---|
| 1541 | * @param input a <code>File</code> to read from.
|
---|
| 1542 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color, if any.
|
---|
| 1543 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
| 1544 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
| 1545 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
| 1546 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
| 1547 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
| 1548 | *
|
---|
| 1549 | * @return a <code>BufferedImage</code> containing the decoded
|
---|
| 1550 | * contents of the input, or <code>null</code>.
|
---|
| 1551 | *
|
---|
| 1552 | * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
|
---|
| 1553 | * @throws IOException if an error occurs during reading.
|
---|
[8459] | 1554 | * @see BufferedImage#getProperty
|
---|
[7132] | 1555 | * @since 7132
|
---|
| 1556 | */
|
---|
| 1557 | public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
| 1558 | CheckParameterUtil.ensureParameterNotNull(input, "input");
|
---|
| 1559 | if (!input.canRead()) {
|
---|
| 1560 | throw new IIOException("Can't read input file!");
|
---|
| 1561 | }
|
---|
| 1562 |
|
---|
| 1563 | ImageInputStream stream = ImageIO.createImageInputStream(input);
|
---|
| 1564 | if (stream == null) {
|
---|
| 1565 | throw new IIOException("Can't create an ImageInputStream!");
|
---|
| 1566 | }
|
---|
| 1567 | BufferedImage bi = read(stream, readMetadata, enforceTransparency);
|
---|
| 1568 | if (bi == null) {
|
---|
| 1569 | stream.close();
|
---|
| 1570 | }
|
---|
| 1571 | return bi;
|
---|
| 1572 | }
|
---|
| 1573 |
|
---|
| 1574 | /**
|
---|
| 1575 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
| 1576 | * a supplied <code>InputStream</code> with an <code>ImageReader</code>
|
---|
| 1577 | * chosen automatically from among those currently registered.
|
---|
| 1578 | * The <code>InputStream</code> is wrapped in an
|
---|
| 1579 | * <code>ImageInputStream</code>. If no registered
|
---|
| 1580 | * <code>ImageReader</code> claims to be able to read the
|
---|
| 1581 | * resulting stream, <code>null</code> is returned.
|
---|
| 1582 | *
|
---|
| 1583 | * <p> The current cache settings from <code>getUseCache</code>and
|
---|
| 1584 | * <code>getCacheDirectory</code> will be used to control caching in the
|
---|
| 1585 | * <code>ImageInputStream</code> that is created.
|
---|
| 1586 | *
|
---|
| 1587 | * <p> This method does not attempt to locate
|
---|
| 1588 | * <code>ImageReader</code>s that can read directly from an
|
---|
| 1589 | * <code>InputStream</code>; that may be accomplished using
|
---|
| 1590 | * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
|
---|
| 1591 | *
|
---|
| 1592 | * <p> This method <em>does not</em> close the provided
|
---|
| 1593 | * <code>InputStream</code> after the read operation has completed;
|
---|
| 1594 | * it is the responsibility of the caller to close the stream, if desired.
|
---|
| 1595 | *
|
---|
| 1596 | * @param input an <code>InputStream</code> to read from.
|
---|
| 1597 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
|
---|
| 1598 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
| 1599 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
| 1600 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
| 1601 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
| 1602 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
| 1603 | *
|
---|
| 1604 | * @return a <code>BufferedImage</code> containing the decoded
|
---|
| 1605 | * contents of the input, or <code>null</code>.
|
---|
| 1606 | *
|
---|
| 1607 | * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
|
---|
| 1608 | * @throws IOException if an error occurs during reading.
|
---|
| 1609 | * @since 7132
|
---|
| 1610 | */
|
---|
| 1611 | public static BufferedImage read(InputStream input, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
| 1612 | CheckParameterUtil.ensureParameterNotNull(input, "input");
|
---|
| 1613 |
|
---|
| 1614 | ImageInputStream stream = ImageIO.createImageInputStream(input);
|
---|
| 1615 | BufferedImage bi = read(stream, readMetadata, enforceTransparency);
|
---|
| 1616 | if (bi == null) {
|
---|
| 1617 | stream.close();
|
---|
| 1618 | }
|
---|
| 1619 | return bi;
|
---|
| 1620 | }
|
---|
| 1621 |
|
---|
| 1622 | /**
|
---|
| 1623 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
| 1624 | * a supplied <code>URL</code> with an <code>ImageReader</code>
|
---|
| 1625 | * chosen automatically from among those currently registered. An
|
---|
| 1626 | * <code>InputStream</code> is obtained from the <code>URL</code>,
|
---|
| 1627 | * which is wrapped in an <code>ImageInputStream</code>. If no
|
---|
| 1628 | * registered <code>ImageReader</code> claims to be able to read
|
---|
| 1629 | * the resulting stream, <code>null</code> is returned.
|
---|
| 1630 | *
|
---|
| 1631 | * <p> The current cache settings from <code>getUseCache</code>and
|
---|
| 1632 | * <code>getCacheDirectory</code> will be used to control caching in the
|
---|
| 1633 | * <code>ImageInputStream</code> that is created.
|
---|
| 1634 | *
|
---|
| 1635 | * <p> This method does not attempt to locate
|
---|
| 1636 | * <code>ImageReader</code>s that can read directly from a
|
---|
| 1637 | * <code>URL</code>; that may be accomplished using
|
---|
| 1638 | * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
|
---|
| 1639 | *
|
---|
| 1640 | * @param input a <code>URL</code> to read from.
|
---|
| 1641 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
|
---|
| 1642 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
| 1643 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
| 1644 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
| 1645 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
| 1646 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
| 1647 | *
|
---|
| 1648 | * @return a <code>BufferedImage</code> containing the decoded
|
---|
| 1649 | * contents of the input, or <code>null</code>.
|
---|
| 1650 | *
|
---|
| 1651 | * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
|
---|
| 1652 | * @throws IOException if an error occurs during reading.
|
---|
| 1653 | * @since 7132
|
---|
| 1654 | */
|
---|
| 1655 | public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
| 1656 | CheckParameterUtil.ensureParameterNotNull(input, "input");
|
---|
| 1657 |
|
---|
| 1658 | InputStream istream = null;
|
---|
| 1659 | try {
|
---|
| 1660 | istream = input.openStream();
|
---|
| 1661 | } catch (IOException e) {
|
---|
| 1662 | throw new IIOException("Can't get input stream from URL!", e);
|
---|
| 1663 | }
|
---|
| 1664 | ImageInputStream stream = ImageIO.createImageInputStream(istream);
|
---|
| 1665 | BufferedImage bi;
|
---|
| 1666 | try {
|
---|
| 1667 | bi = read(stream, readMetadata, enforceTransparency);
|
---|
| 1668 | if (bi == null) {
|
---|
| 1669 | stream.close();
|
---|
| 1670 | }
|
---|
| 1671 | } finally {
|
---|
| 1672 | istream.close();
|
---|
| 1673 | }
|
---|
| 1674 | return bi;
|
---|
| 1675 | }
|
---|
| 1676 |
|
---|
| 1677 | /**
|
---|
| 1678 | * Returns a <code>BufferedImage</code> as the result of decoding
|
---|
| 1679 | * a supplied <code>ImageInputStream</code> with an
|
---|
| 1680 | * <code>ImageReader</code> chosen automatically from among those
|
---|
| 1681 | * currently registered. If no registered
|
---|
| 1682 | * <code>ImageReader</code> claims to be able to read the stream,
|
---|
| 1683 | * <code>null</code> is returned.
|
---|
| 1684 | *
|
---|
| 1685 | * <p> Unlike most other methods in this class, this method <em>does</em>
|
---|
| 1686 | * close the provided <code>ImageInputStream</code> after the read
|
---|
| 1687 | * operation has completed, unless <code>null</code> is returned,
|
---|
| 1688 | * in which case this method <em>does not</em> close the stream.
|
---|
| 1689 | *
|
---|
| 1690 | * @param stream an <code>ImageInputStream</code> to read from.
|
---|
| 1691 | * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
|
---|
| 1692 | * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
|
---|
| 1693 | * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
|
---|
| 1694 | * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
|
---|
| 1695 | * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
|
---|
| 1696 | * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
|
---|
| 1697 | *
|
---|
| 1698 | * @return a <code>BufferedImage</code> containing the decoded
|
---|
| 1699 | * contents of the input, or <code>null</code>.
|
---|
| 1700 | *
|
---|
| 1701 | * @throws IllegalArgumentException if <code>stream</code> is <code>null</code>.
|
---|
| 1702 | * @throws IOException if an error occurs during reading.
|
---|
| 1703 | * @since 7132
|
---|
| 1704 | */
|
---|
| 1705 | public static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency) throws IOException {
|
---|
| 1706 | CheckParameterUtil.ensureParameterNotNull(stream, "stream");
|
---|
| 1707 |
|
---|
| 1708 | Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
|
---|
| 1709 | if (!iter.hasNext()) {
|
---|
| 1710 | return null;
|
---|
| 1711 | }
|
---|
| 1712 |
|
---|
| 1713 | ImageReader reader = iter.next();
|
---|
| 1714 | ImageReadParam param = reader.getDefaultReadParam();
|
---|
| 1715 | reader.setInput(stream, true, !readMetadata && !enforceTransparency);
|
---|
| 1716 | BufferedImage bi;
|
---|
| 1717 | try {
|
---|
| 1718 | bi = reader.read(0, param);
|
---|
| 1719 | if (bi.getTransparency() != Transparency.TRANSLUCENT && (readMetadata || enforceTransparency)) {
|
---|
[7499] | 1720 | Color color = getTransparentColor(bi.getColorModel(), reader);
|
---|
[7132] | 1721 | if (color != null) {
|
---|
| 1722 | Hashtable<String, Object> properties = new Hashtable<>(1);
|
---|
| 1723 | properties.put(PROP_TRANSPARENCY_COLOR, color);
|
---|
| 1724 | bi = new BufferedImage(bi.getColorModel(), bi.getRaster(), bi.isAlphaPremultiplied(), properties);
|
---|
| 1725 | if (enforceTransparency) {
|
---|
[7495] | 1726 | if (Main.isTraceEnabled()) {
|
---|
| 1727 | Main.trace("Enforcing image transparency of "+stream+" for "+color);
|
---|
[7132] | 1728 | }
|
---|
| 1729 | bi = makeImageTransparent(bi, color);
|
---|
| 1730 | }
|
---|
| 1731 | }
|
---|
| 1732 | }
|
---|
| 1733 | } finally {
|
---|
| 1734 | reader.dispose();
|
---|
| 1735 | stream.close();
|
---|
| 1736 | }
|
---|
| 1737 | return bi;
|
---|
| 1738 | }
|
---|
| 1739 |
|
---|
[8540] | 1740 | // CHECKSTYLE.OFF: LineLength
|
---|
| 1741 |
|
---|
[7132] | 1742 | /**
|
---|
| 1743 | * Returns the {@code TransparentColor} defined in image reader metadata.
|
---|
[7499] | 1744 | * @param model The image color model
|
---|
[7132] | 1745 | * @param reader The image reader
|
---|
| 1746 | * @return the {@code TransparentColor} defined in image reader metadata, or {@code null}
|
---|
| 1747 | * @throws IOException if an error occurs during reading
|
---|
[10580] | 1748 | * @see <a href="http://docs.oracle.com/javase/8/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html">javax_imageio_1.0 metadata</a>
|
---|
[7499] | 1749 | * @since 7499
|
---|
[7132] | 1750 | */
|
---|
[7499] | 1751 | public static Color getTransparentColor(ColorModel model, ImageReader reader) throws IOException {
|
---|
[8540] | 1752 | // CHECKSTYLE.ON: LineLength
|
---|
[7313] | 1753 | try {
|
---|
| 1754 | IIOMetadata metadata = reader.getImageMetadata(0);
|
---|
| 1755 | if (metadata != null) {
|
---|
| 1756 | String[] formats = metadata.getMetadataFormatNames();
|
---|
| 1757 | if (formats != null) {
|
---|
| 1758 | for (String f : formats) {
|
---|
| 1759 | if ("javax_imageio_1.0".equals(f)) {
|
---|
| 1760 | Node root = metadata.getAsTree(f);
|
---|
| 1761 | if (root instanceof Element) {
|
---|
[8510] | 1762 | NodeList list = ((Element) root).getElementsByTagName("TransparentColor");
|
---|
[7313] | 1763 | if (list.getLength() > 0) {
|
---|
| 1764 | Node item = list.item(0);
|
---|
| 1765 | if (item instanceof Element) {
|
---|
[7499] | 1766 | // Handle different color spaces (tested with RGB and grayscale)
|
---|
[8510] | 1767 | String value = ((Element) item).getAttribute("value");
|
---|
[7499] | 1768 | if (!value.isEmpty()) {
|
---|
| 1769 | String[] s = value.split(" ");
|
---|
| 1770 | if (s.length == 3) {
|
---|
| 1771 | return parseRGB(s);
|
---|
| 1772 | } else if (s.length == 1) {
|
---|
| 1773 | int pixel = Integer.parseInt(s[0]);
|
---|
| 1774 | int r = model.getRed(pixel);
|
---|
| 1775 | int g = model.getGreen(pixel);
|
---|
| 1776 | int b = model.getBlue(pixel);
|
---|
[8510] | 1777 | return new Color(r, g, b);
|
---|
[7499] | 1778 | } else {
|
---|
| 1779 | Main.warn("Unable to translate TransparentColor '"+value+"' with color model "+model);
|
---|
| 1780 | }
|
---|
[7132] | 1781 | }
|
---|
[7402] | 1782 | }
|
---|
[7313] | 1783 | }
|
---|
[7132] | 1784 | }
|
---|
[7313] | 1785 | break;
|
---|
[7132] | 1786 | }
|
---|
| 1787 | }
|
---|
| 1788 | }
|
---|
| 1789 | }
|
---|
[7499] | 1790 | } catch (IIOException | NumberFormatException e) {
|
---|
[7313] | 1791 | // JAI doesn't like some JPEG files with error "Inconsistent metadata read from stream" (see #10267)
|
---|
| 1792 | Main.warn(e);
|
---|
[12508] | 1793 | } catch (UnsatisfiedLinkError e) {
|
---|
| 1794 | // On Windows, ComponentColorModel.getRGBComponent can fail with "UnsatisfiedLinkError: no awt in java.library.path", see #13973
|
---|
| 1795 | Main.error(e);
|
---|
[7132] | 1796 | }
|
---|
| 1797 | return null;
|
---|
| 1798 | }
|
---|
| 1799 |
|
---|
[11747] | 1800 | private static Color parseRGB(String... s) {
|
---|
[7402] | 1801 | int[] rgb = new int[3];
|
---|
| 1802 | try {
|
---|
[8510] | 1803 | for (int i = 0; i < 3; i++) {
|
---|
[7402] | 1804 | rgb[i] = Integer.parseInt(s[i]);
|
---|
| 1805 | }
|
---|
| 1806 | return new Color(rgb[0], rgb[1], rgb[2]);
|
---|
| 1807 | } catch (IllegalArgumentException e) {
|
---|
| 1808 | Main.error(e);
|
---|
| 1809 | return null;
|
---|
| 1810 | }
|
---|
| 1811 | }
|
---|
| 1812 |
|
---|
[7132] | 1813 | /**
|
---|
| 1814 | * Returns a transparent version of the given image, based on the given transparent color.
|
---|
| 1815 | * @param bi The image to convert
|
---|
| 1816 | * @param color The transparent color
|
---|
| 1817 | * @return The same image as {@code bi} where all pixels of the given color are transparent.
|
---|
| 1818 | * This resulting image has also the special property {@link #PROP_TRANSPARENCY_FORCED} set to {@code color}
|
---|
| 1819 | * @see BufferedImage#getProperty
|
---|
| 1820 | * @see #isTransparencyForced
|
---|
[8412] | 1821 | * @since 7132
|
---|
[7132] | 1822 | */
|
---|
| 1823 | public static BufferedImage makeImageTransparent(BufferedImage bi, Color color) {
|
---|
| 1824 | // the color we are looking for. Alpha bits are set to opaque
|
---|
[7495] | 1825 | final int markerRGB = color.getRGB() | 0xFF000000;
|
---|
[7132] | 1826 | ImageFilter filter = new RGBImageFilter() {
|
---|
| 1827 | @Override
|
---|
| 1828 | public int filterRGB(int x, int y, int rgb) {
|
---|
| 1829 | if ((rgb | 0xFF000000) == markerRGB) {
|
---|
| 1830 | // Mark the alpha bits as zero - transparent
|
---|
| 1831 | return 0x00FFFFFF & rgb;
|
---|
| 1832 | } else {
|
---|
| 1833 | return rgb;
|
---|
| 1834 | }
|
---|
| 1835 | }
|
---|
| 1836 | };
|
---|
| 1837 | ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
|
---|
| 1838 | Image img = Toolkit.getDefaultToolkit().createImage(ip);
|
---|
| 1839 | ColorModel colorModel = ColorModel.getRGBdefault();
|
---|
| 1840 | WritableRaster raster = colorModel.createCompatibleWritableRaster(img.getWidth(null), img.getHeight(null));
|
---|
| 1841 | String[] names = bi.getPropertyNames();
|
---|
| 1842 | Hashtable<String, Object> properties = new Hashtable<>(1 + (names != null ? names.length : 0));
|
---|
| 1843 | if (names != null) {
|
---|
| 1844 | for (String name : names) {
|
---|
| 1845 | properties.put(name, bi.getProperty(name));
|
---|
| 1846 | }
|
---|
| 1847 | }
|
---|
| 1848 | properties.put(PROP_TRANSPARENCY_FORCED, Boolean.TRUE);
|
---|
| 1849 | BufferedImage result = new BufferedImage(colorModel, raster, false, properties);
|
---|
| 1850 | Graphics2D g2 = result.createGraphics();
|
---|
| 1851 | g2.drawImage(img, 0, 0, null);
|
---|
| 1852 | g2.dispose();
|
---|
| 1853 | return result;
|
---|
| 1854 | }
|
---|
| 1855 |
|
---|
| 1856 | /**
|
---|
| 1857 | * Determines if the transparency of the given {@code BufferedImage} has been enforced by a previous call to {@link #makeImageTransparent}.
|
---|
| 1858 | * @param bi The {@code BufferedImage} to test
|
---|
| 1859 | * @return {@code true} if the transparency of {@code bi} has been enforced by a previous call to {@code makeImageTransparent}.
|
---|
[8412] | 1860 | * @see #makeImageTransparent
|
---|
[7132] | 1861 | * @since 7132
|
---|
| 1862 | */
|
---|
| 1863 | public static boolean isTransparencyForced(BufferedImage bi) {
|
---|
| 1864 | return bi != null && !bi.getProperty(PROP_TRANSPARENCY_FORCED).equals(Image.UndefinedProperty);
|
---|
| 1865 | }
|
---|
| 1866 |
|
---|
| 1867 | /**
|
---|
[9705] | 1868 | * Determines if the given {@code BufferedImage} has a transparent color determined by a previous call to {@link #read}.
|
---|
[7132] | 1869 | * @param bi The {@code BufferedImage} to test
|
---|
| 1870 | * @return {@code true} if {@code bi} has a transparent color determined by a previous call to {@code read}.
|
---|
[8412] | 1871 | * @see #read
|
---|
[7132] | 1872 | * @since 7132
|
---|
| 1873 | */
|
---|
| 1874 | public static boolean hasTransparentColor(BufferedImage bi) {
|
---|
| 1875 | return bi != null && !bi.getProperty(PROP_TRANSPARENCY_COLOR).equals(Image.UndefinedProperty);
|
---|
| 1876 | }
|
---|
[8412] | 1877 |
|
---|
| 1878 | /**
|
---|
| 1879 | * Shutdown background image fetcher.
|
---|
| 1880 | * @param now if {@code true}, attempts to stop all actively executing tasks, halts the processing of waiting tasks.
|
---|
| 1881 | * if {@code false}, initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted
|
---|
| 1882 | * @since 8412
|
---|
| 1883 | */
|
---|
| 1884 | public static void shutdown(boolean now) {
|
---|
| 1885 | if (now) {
|
---|
| 1886 | IMAGE_FETCHER.shutdownNow();
|
---|
| 1887 | } else {
|
---|
| 1888 | IMAGE_FETCHER.shutdown();
|
---|
| 1889 | }
|
---|
| 1890 | }
|
---|
[17] | 1891 | }
|
---|