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

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

fix some Sonar issues recently introduced

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