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

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

don't crash when data image url is broken

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