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

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

see #10684 - remove remaining overlay() calls

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