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

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

checkstyle, javadoc

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