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

Last change on this file since 10160 was 10140, checked in by bastiK, 8 years ago

fixed #12748 - Error dialog after deleting a new inserted node

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