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

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

sonar - fb-contrib - minor performance improvements:

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