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