source: josm/trunk/src/org/openstreetmap/josm/tools/ImageProvider.java@ 9704

Last change on this file since 9704 was 9691, checked in by simon04, 8 years ago

fix #12452 - icons in relation list display low priority icons

Prefer more specific presets w.r.t. the supported types

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