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

Last change on this file since 10001 was 10001, checked in by Don-vip, 8 years ago

sonar - Local variable and method parameter names should comply with a naming convention

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