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

Last change on this file since 9645 was 9637, checked in by stoecker, 8 years ago

fix coverity 1349920 and 1349921

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