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

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

simplify URL encoding/decoding

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