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

Last change on this file since 8096 was 8096, checked in by stoecker, 9 years ago

fix typo

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