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

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

fix remaining checkstyle issues

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