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

Last change on this file since 9732 was 9705, checked in by simon04, 8 years ago

fix #12409 - Refactor ImageProvider.ImageSizes

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