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

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

fix #10695 - NPE

  • Property svn:eol-style set to native
File size: 58.8 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 (mediatype != null && mediatype.contains("image/svg+xml")) {
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 return new ImageResource(read(new ByteArrayInputStream(bytes), false, true));
700 } catch (IOException e) {
701 Main.warn("IOException while reading image: "+e.getMessage());
702 }
703 }
704 }
705 return null;
706 } catch (UnsupportedEncodingException ex) {
707 throw new RuntimeException(ex.getMessage(), ex);
708 }
709 }
710
711 private static ImageResource getIfAvailableWiki(String name, ImageType type) {
712 final Collection<String> defaultBaseUrls = Arrays.asList(
713 "http://wiki.openstreetmap.org/w/images/",
714 "http://upload.wikimedia.org/wikipedia/commons/",
715 "http://wiki.openstreetmap.org/wiki/File:"
716 );
717 final Collection<String> baseUrls = Main.pref.getCollection("image-provider.wiki.urls", defaultBaseUrls);
718
719 final String fn = name.substring(name.lastIndexOf('/') + 1);
720
721 ImageResource result = null;
722 for (String b : baseUrls) {
723 String url;
724 if (b.endsWith(":")) {
725 url = getImgUrlFromWikiInfoPage(b, fn);
726 if (url == null) {
727 continue;
728 }
729 } else {
730 final String fn_md5 = Utils.md5Hex(fn);
731 url = b + fn_md5.substring(0,1) + "/" + fn_md5.substring(0,2) + "/" + fn;
732 }
733 result = getIfAvailableHttp(url, type);
734 if (result != null) {
735 break;
736 }
737 }
738 return result;
739 }
740
741 private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
742 try (ZipFile zipFile = new ZipFile(archive, StandardCharsets.UTF_8)) {
743 if (inArchiveDir == null || ".".equals(inArchiveDir)) {
744 inArchiveDir = "";
745 } else if (!inArchiveDir.isEmpty()) {
746 inArchiveDir += "/";
747 }
748 String entryName = inArchiveDir + fullName;
749 ZipEntry entry = zipFile.getEntry(entryName);
750 if (entry != null) {
751 int size = (int)entry.getSize();
752 int offs = 0;
753 byte[] buf = new byte[size];
754 try (InputStream is = zipFile.getInputStream(entry)) {
755 switch (type) {
756 case SVG:
757 URI uri = getSvgUniverse().loadSVG(is, entryName);
758 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
759 return svg == null ? null : new ImageResource(svg);
760 case OTHER:
761 while(size > 0)
762 {
763 int l = is.read(buf, offs, size);
764 offs += l;
765 size -= l;
766 }
767 BufferedImage img = null;
768 try {
769 img = read(new ByteArrayInputStream(buf), false, false);
770 } catch (IOException e) {
771 Main.warn(e);
772 }
773 return img == null ? null : new ImageResource(img);
774 default:
775 throw new AssertionError("Unknown ImageType: "+type);
776 }
777 }
778 }
779 } catch (Exception e) {
780 Main.warn(tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
781 }
782 return null;
783 }
784
785 private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
786 switch (type) {
787 case SVG:
788 URI uri = getSvgUniverse().loadSVG(path);
789 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
790 return svg == null ? null : new ImageResource(svg);
791 case OTHER:
792 BufferedImage img = null;
793 try {
794 // See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
795 // This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
796 // hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/828c4fedd29f/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
797 img = read(path, false, true);
798 if (Main.isDebugEnabled() && isTransparencyForced(img)) {
799 Main.debug("Transparency has been forced for image "+path.toExternalForm());
800 }
801 } catch (IOException e) {
802 Main.warn(e);
803 }
804 return img == null ? null : new ImageResource(img);
805 default:
806 throw new AssertionError();
807 }
808 }
809
810 private static URL getImageUrl(String path, String name, Collection<ClassLoader> additionalClassLoaders) {
811 if (path != null && path.startsWith("resource://")) {
812 String p = path.substring("resource://".length());
813 Collection<ClassLoader> classLoaders = new ArrayList<>(PluginHandler.getResourceClassLoaders());
814 if (additionalClassLoaders != null) {
815 classLoaders.addAll(additionalClassLoaders);
816 }
817 for (ClassLoader source : classLoaders) {
818 URL res;
819 if ((res = source.getResource(p + name)) != null)
820 return res;
821 }
822 } else {
823 File f = new File(path, name);
824 if ((path != null || f.isAbsolute()) && f.exists())
825 return Utils.fileToURL(f);
826 }
827 return null;
828 }
829
830 private static URL getImageUrl(String imageName, Collection<String> dirs, Collection<ClassLoader> additionalClassLoaders) {
831 URL u = null;
832
833 // Try passed directories first
834 if (dirs != null) {
835 for (String name : dirs) {
836 try {
837 u = getImageUrl(name, imageName, additionalClassLoaders);
838 if (u != null)
839 return u;
840 } catch (SecurityException e) {
841 Main.warn(tr(
842 "Failed to access directory ''{0}'' for security reasons. Exception was: {1}",
843 name, e.toString()));
844 }
845
846 }
847 }
848 // Try user-preference directory
849 String dir = Main.pref.getPreferencesDir() + "images";
850 try {
851 u = getImageUrl(dir, imageName, additionalClassLoaders);
852 if (u != null)
853 return u;
854 } catch (SecurityException e) {
855 Main.warn(tr(
856 "Failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
857 .toString()));
858 }
859
860 // Absolute path?
861 u = getImageUrl(null, imageName, additionalClassLoaders);
862 if (u != null)
863 return u;
864
865 // Try plugins and josm classloader
866 u = getImageUrl("resource://images/", imageName, additionalClassLoaders);
867 if (u != null)
868 return u;
869
870 // Try all other resource directories
871 for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
872 u = getImageUrl(location + "images", imageName, additionalClassLoaders);
873 if (u != null)
874 return u;
875 u = getImageUrl(location, imageName, additionalClassLoaders);
876 if (u != null)
877 return u;
878 }
879
880 return null;
881 }
882
883 /** Quit parsing, when a certain condition is met */
884 private static class SAXReturnException extends SAXException {
885 private final String result;
886
887 public SAXReturnException(String result) {
888 this.result = result;
889 }
890
891 public String getResult() {
892 return result;
893 }
894 }
895
896 /**
897 * Reads the wiki page on a certain file in html format in order to find the real image URL.
898 */
899 private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
900 try {
901 final XMLReader parser = XMLReaderFactory.createXMLReader();
902 parser.setContentHandler(new DefaultHandler() {
903 @Override
904 public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
905 if ("img".equalsIgnoreCase(localName)) {
906 String val = atts.getValue("src");
907 if (val.endsWith(fn))
908 throw new SAXReturnException(val); // parsing done, quit early
909 }
910 }
911 });
912
913 parser.setEntityResolver(new EntityResolver() {
914 @Override
915 public InputSource resolveEntity (String publicId, String systemId) {
916 return new InputSource(new ByteArrayInputStream(new byte[0]));
917 }
918 });
919
920 CachedFile cf = new CachedFile(base + fn).setDestDir(new File(Main.pref.getPreferencesDir(), "images").toString());
921 try (InputStream is = cf.getInputStream()) {
922 parser.parse(new InputSource(is));
923 }
924 } catch (SAXReturnException r) {
925 return r.getResult();
926 } catch (Exception e) {
927 Main.warn("Parsing " + base + fn + " failed:\n" + e);
928 return null;
929 }
930 Main.warn("Parsing " + base + fn + " failed: Unexpected content.");
931 return null;
932 }
933
934 public static Cursor getCursor(String name, String overlay) {
935 ImageIcon img = get("cursor", name);
936 if (overlay != null) {
937 img = overlay(img, ImageProvider.get("cursor/modifier/" + overlay), OverlayPosition.SOUTHEAST);
938 }
939 if (GraphicsEnvironment.isHeadless()) {
940 Main.warn("Cursors are not available in headless mode. Returning null for '"+name+"'");
941 return null;
942 }
943 return Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
944 "crosshair".equals(name) ? new Point(10, 10) : new Point(3, 2), "Cursor");
945 }
946
947 /**
948 * Decorate one icon with an overlay icon.
949 *
950 * @param ground the base image
951 * @param overlay the overlay image (can be smaller than the base image)
952 * @param pos position of the overlay image inside the base image (positioned
953 * in one of the corners)
954 * @return an icon that represent the overlay of the two given icons. The second icon is layed
955 * on the first relative to the given position.
956 * FIXME: This function does not fit into the ImageProvider concept as public function!
957 * Overlay should be handled like all the other functions only settings arguments and
958 * overlay must be transparent in the background.
959 * Also scaling is not cared about with current implementation.
960 */
961 @Deprecated
962 public static ImageIcon overlay(Icon ground, Icon overlay, OverlayPosition pos) {
963 int w = ground.getIconWidth();
964 int h = ground.getIconHeight();
965 int wo = overlay.getIconWidth();
966 int ho = overlay.getIconHeight();
967 BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
968 Graphics g = img.createGraphics();
969 ground.paintIcon(null, g, 0, 0);
970 int x = 0, y = 0;
971 switch (pos) {
972 case NORTHWEST:
973 x = 0;
974 y = 0;
975 break;
976 case NORTHEAST:
977 x = w - wo;
978 y = 0;
979 break;
980 case SOUTHWEST:
981 x = 0;
982 y = h - ho;
983 break;
984 case SOUTHEAST:
985 x = w - wo;
986 y = h - ho;
987 break;
988 }
989 overlay.paintIcon(null, g, x, y);
990 return new ImageIcon(img);
991 }
992
993 /** 90 degrees in radians units */
994 static final double DEGREE_90 = 90.0 * Math.PI / 180.0;
995
996 /**
997 * Creates a rotated version of the input image.
998 *
999 * @param img the image to be rotated.
1000 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
1001 * will mod it with 360 before using it. More over for caching performance, it will be rounded to
1002 * an entire value between 0 and 360.
1003 *
1004 * @return the image after rotating.
1005 * @since 6172
1006 */
1007 public static Image createRotatedImage(Image img, double rotatedAngle) {
1008 return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
1009 }
1010
1011 /**
1012 * Creates a rotated version of the input image, scaled to the given dimension.
1013 *
1014 * @param img the image to be rotated.
1015 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
1016 * will mod it with 360 before using it. More over for caching performance, it will be rounded to
1017 * an entire value between 0 and 360.
1018 * @param dimension The requested dimensions. Use (-1,-1) for the original size
1019 * and (width, -1) to set the width, but otherwise scale the image proportionally.
1020 * @return the image after rotating and scaling.
1021 * @since 6172
1022 */
1023 public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
1024 CheckParameterUtil.ensureParameterNotNull(img, "img");
1025
1026 // convert rotatedAngle to an integer value from 0 to 360
1027 Long originalAngle = Math.round(rotatedAngle % 360);
1028 if (rotatedAngle != 0 && originalAngle == 0) {
1029 originalAngle = 360L;
1030 }
1031
1032 ImageResource imageResource = null;
1033
1034 synchronized (ROTATE_CACHE) {
1035 Map<Long, ImageResource> cacheByAngle = ROTATE_CACHE.get(img);
1036 if (cacheByAngle == null) {
1037 ROTATE_CACHE.put(img, cacheByAngle = new HashMap<>());
1038 }
1039
1040 imageResource = cacheByAngle.get(originalAngle);
1041
1042 if (imageResource == null) {
1043 // convert originalAngle to a value from 0 to 90
1044 double angle = originalAngle % 90;
1045 if (originalAngle != 0.0 && angle == 0.0) {
1046 angle = 90.0;
1047 }
1048
1049 double radian = Math.toRadians(angle);
1050
1051 new ImageIcon(img); // load completely
1052 int iw = img.getWidth(null);
1053 int ih = img.getHeight(null);
1054 int w;
1055 int h;
1056
1057 if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
1058 w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
1059 h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
1060 } else {
1061 w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
1062 h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
1063 }
1064 Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
1065 cacheByAngle.put(originalAngle, imageResource = new ImageResource(image));
1066 Graphics g = image.getGraphics();
1067 Graphics2D g2d = (Graphics2D) g.create();
1068
1069 // calculate the center of the icon.
1070 int cx = iw / 2;
1071 int cy = ih / 2;
1072
1073 // move the graphics center point to the center of the icon.
1074 g2d.translate(w / 2, h / 2);
1075
1076 // rotate the graphics about the center point of the icon
1077 g2d.rotate(Math.toRadians(originalAngle));
1078
1079 g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
1080 g2d.drawImage(img, -cx, -cy, null);
1081
1082 g2d.dispose();
1083 new ImageIcon(image); // load completely
1084 }
1085 return imageResource.getImageIcon(dimension).getImage();
1086 }
1087 }
1088
1089 /**
1090 * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
1091 *
1092 * @param img the image to be scaled down.
1093 * @param maxSize the maximum size in pixels (both for width and height)
1094 *
1095 * @return the image after scaling.
1096 * @since 6172
1097 */
1098 public static Image createBoundedImage(Image img, int maxSize) {
1099 return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
1100 }
1101
1102 /**
1103 * Replies the icon for an OSM primitive type
1104 * @param type the type
1105 * @return the icon
1106 */
1107 public static ImageIcon get(OsmPrimitiveType type) {
1108 CheckParameterUtil.ensureParameterNotNull(type, "type");
1109 return get("data", type.getAPIName());
1110 }
1111
1112 public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
1113 float realWidth = svg.getWidth();
1114 float realHeight = svg.getHeight();
1115 int width = Math.round(realWidth);
1116 int height = Math.round(realHeight);
1117 Double scaleX = null, scaleY = null;
1118 if (dim.width != -1) {
1119 width = dim.width;
1120 scaleX = (double) width / realWidth;
1121 if (dim.height == -1) {
1122 scaleY = scaleX;
1123 height = (int) Math.round(realHeight * scaleY);
1124 } else {
1125 height = dim.height;
1126 scaleY = (double) height / realHeight;
1127 }
1128 } else if (dim.height != -1) {
1129 height = dim.height;
1130 scaleX = scaleY = (double) height / realHeight;
1131 width = (int) Math.round(realWidth * scaleX);
1132 }
1133 if (width == 0 || height == 0) {
1134 return null;
1135 }
1136 BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
1137 Graphics2D g = img.createGraphics();
1138 g.setClip(0, 0, width, height);
1139 if (scaleX != null && scaleY != null) {
1140 g.scale(scaleX, scaleY);
1141 }
1142 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
1143 try {
1144 svg.render(g);
1145 } catch (SVGException ex) {
1146 return null;
1147 }
1148 return img;
1149 }
1150
1151 private static SVGUniverse getSvgUniverse() {
1152 if (svgUniverse == null) {
1153 svgUniverse = new SVGUniverse();
1154 }
1155 return svgUniverse;
1156 }
1157
1158 /**
1159 * Returns a <code>BufferedImage</code> as the result of decoding
1160 * a supplied <code>File</code> with an <code>ImageReader</code>
1161 * chosen automatically from among those currently registered.
1162 * The <code>File</code> is wrapped in an
1163 * <code>ImageInputStream</code>. If no registered
1164 * <code>ImageReader</code> claims to be able to read the
1165 * resulting stream, <code>null</code> is returned.
1166 *
1167 * <p> The current cache settings from <code>getUseCache</code>and
1168 * <code>getCacheDirectory</code> will be used to control caching in the
1169 * <code>ImageInputStream</code> that is created.
1170 *
1171 * <p> Note that there is no <code>read</code> method that takes a
1172 * filename as a <code>String</code>; use this method instead after
1173 * creating a <code>File</code> from the filename.
1174 *
1175 * <p> This method does not attempt to locate
1176 * <code>ImageReader</code>s that can read directly from a
1177 * <code>File</code>; that may be accomplished using
1178 * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1179 *
1180 * @param input a <code>File</code> to read from.
1181 * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color, if any.
1182 * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1183 * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1184 * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1185 * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1186 * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1187 *
1188 * @return a <code>BufferedImage</code> containing the decoded
1189 * contents of the input, or <code>null</code>.
1190 *
1191 * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1192 * @throws IOException if an error occurs during reading.
1193 * @since 7132
1194 * @see BufferedImage#getProperty
1195 */
1196 public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1197 CheckParameterUtil.ensureParameterNotNull(input, "input");
1198 if (!input.canRead()) {
1199 throw new IIOException("Can't read input file!");
1200 }
1201
1202 ImageInputStream stream = ImageIO.createImageInputStream(input);
1203 if (stream == null) {
1204 throw new IIOException("Can't create an ImageInputStream!");
1205 }
1206 BufferedImage bi = read(stream, readMetadata, enforceTransparency);
1207 if (bi == null) {
1208 stream.close();
1209 }
1210 return bi;
1211 }
1212
1213 /**
1214 * Returns a <code>BufferedImage</code> as the result of decoding
1215 * a supplied <code>InputStream</code> with an <code>ImageReader</code>
1216 * chosen automatically from among those currently registered.
1217 * The <code>InputStream</code> is wrapped in an
1218 * <code>ImageInputStream</code>. If no registered
1219 * <code>ImageReader</code> claims to be able to read the
1220 * resulting stream, <code>null</code> is returned.
1221 *
1222 * <p> The current cache settings from <code>getUseCache</code>and
1223 * <code>getCacheDirectory</code> will be used to control caching in the
1224 * <code>ImageInputStream</code> that is created.
1225 *
1226 * <p> This method does not attempt to locate
1227 * <code>ImageReader</code>s that can read directly from an
1228 * <code>InputStream</code>; that may be accomplished using
1229 * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1230 *
1231 * <p> This method <em>does not</em> close the provided
1232 * <code>InputStream</code> after the read operation has completed;
1233 * it is the responsibility of the caller to close the stream, if desired.
1234 *
1235 * @param input an <code>InputStream</code> to read from.
1236 * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1237 * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1238 * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1239 * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1240 * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1241 * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1242 *
1243 * @return a <code>BufferedImage</code> containing the decoded
1244 * contents of the input, or <code>null</code>.
1245 *
1246 * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1247 * @throws IOException if an error occurs during reading.
1248 * @since 7132
1249 */
1250 public static BufferedImage read(InputStream input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1251 CheckParameterUtil.ensureParameterNotNull(input, "input");
1252
1253 ImageInputStream stream = ImageIO.createImageInputStream(input);
1254 BufferedImage bi = read(stream, readMetadata, enforceTransparency);
1255 if (bi == null) {
1256 stream.close();
1257 }
1258 return bi;
1259 }
1260
1261 /**
1262 * Returns a <code>BufferedImage</code> as the result of decoding
1263 * a supplied <code>URL</code> with an <code>ImageReader</code>
1264 * chosen automatically from among those currently registered. An
1265 * <code>InputStream</code> is obtained from the <code>URL</code>,
1266 * which is wrapped in an <code>ImageInputStream</code>. If no
1267 * registered <code>ImageReader</code> claims to be able to read
1268 * the resulting stream, <code>null</code> is returned.
1269 *
1270 * <p> The current cache settings from <code>getUseCache</code>and
1271 * <code>getCacheDirectory</code> will be used to control caching in the
1272 * <code>ImageInputStream</code> that is created.
1273 *
1274 * <p> This method does not attempt to locate
1275 * <code>ImageReader</code>s that can read directly from a
1276 * <code>URL</code>; that may be accomplished using
1277 * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1278 *
1279 * @param input a <code>URL</code> to read from.
1280 * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1281 * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1282 * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1283 * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1284 * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1285 * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1286 *
1287 * @return a <code>BufferedImage</code> containing the decoded
1288 * contents of the input, or <code>null</code>.
1289 *
1290 * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1291 * @throws IOException if an error occurs during reading.
1292 * @since 7132
1293 */
1294 public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1295 CheckParameterUtil.ensureParameterNotNull(input, "input");
1296
1297 InputStream istream = null;
1298 try {
1299 istream = input.openStream();
1300 } catch (IOException e) {
1301 throw new IIOException("Can't get input stream from URL!", e);
1302 }
1303 ImageInputStream stream = ImageIO.createImageInputStream(istream);
1304 BufferedImage bi;
1305 try {
1306 bi = read(stream, readMetadata, enforceTransparency);
1307 if (bi == null) {
1308 stream.close();
1309 }
1310 } finally {
1311 istream.close();
1312 }
1313 return bi;
1314 }
1315
1316 /**
1317 * Returns a <code>BufferedImage</code> as the result of decoding
1318 * a supplied <code>ImageInputStream</code> with an
1319 * <code>ImageReader</code> chosen automatically from among those
1320 * currently registered. If no registered
1321 * <code>ImageReader</code> claims to be able to read the stream,
1322 * <code>null</code> is returned.
1323 *
1324 * <p> Unlike most other methods in this class, this method <em>does</em>
1325 * close the provided <code>ImageInputStream</code> after the read
1326 * operation has completed, unless <code>null</code> is returned,
1327 * in which case this method <em>does not</em> close the stream.
1328 *
1329 * @param stream an <code>ImageInputStream</code> to read from.
1330 * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1331 * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1332 * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1333 * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1334 * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1335 * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1336 *
1337 * @return a <code>BufferedImage</code> containing the decoded
1338 * contents of the input, or <code>null</code>.
1339 *
1340 * @throws IllegalArgumentException if <code>stream</code> is <code>null</code>.
1341 * @throws IOException if an error occurs during reading.
1342 * @since 7132
1343 */
1344 public static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency) throws IOException {
1345 CheckParameterUtil.ensureParameterNotNull(stream, "stream");
1346
1347 Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
1348 if (!iter.hasNext()) {
1349 return null;
1350 }
1351
1352 ImageReader reader = iter.next();
1353 ImageReadParam param = reader.getDefaultReadParam();
1354 reader.setInput(stream, true, !readMetadata && !enforceTransparency);
1355 BufferedImage bi;
1356 try {
1357 bi = reader.read(0, param);
1358 if (bi.getTransparency() != Transparency.TRANSLUCENT && (readMetadata || enforceTransparency)) {
1359 Color color = getTransparentColor(bi.getColorModel(), reader);
1360 if (color != null) {
1361 Hashtable<String, Object> properties = new Hashtable<>(1);
1362 properties.put(PROP_TRANSPARENCY_COLOR, color);
1363 bi = new BufferedImage(bi.getColorModel(), bi.getRaster(), bi.isAlphaPremultiplied(), properties);
1364 if (enforceTransparency) {
1365 if (Main.isTraceEnabled()) {
1366 Main.trace("Enforcing image transparency of "+stream+" for "+color);
1367 }
1368 bi = makeImageTransparent(bi, color);
1369 }
1370 }
1371 }
1372 } finally {
1373 reader.dispose();
1374 stream.close();
1375 }
1376 return bi;
1377 }
1378
1379 /**
1380 * Returns the {@code TransparentColor} defined in image reader metadata.
1381 * @param model The image color model
1382 * @param reader The image reader
1383 * @return the {@code TransparentColor} defined in image reader metadata, or {@code null}
1384 * @throws IOException if an error occurs during reading
1385 * @since 7499
1386 * @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>
1387 */
1388 public static Color getTransparentColor(ColorModel model, ImageReader reader) throws IOException {
1389 try {
1390 IIOMetadata metadata = reader.getImageMetadata(0);
1391 if (metadata != null) {
1392 String[] formats = metadata.getMetadataFormatNames();
1393 if (formats != null) {
1394 for (String f : formats) {
1395 if ("javax_imageio_1.0".equals(f)) {
1396 Node root = metadata.getAsTree(f);
1397 if (root instanceof Element) {
1398 NodeList list = ((Element)root).getElementsByTagName("TransparentColor");
1399 if (list.getLength() > 0) {
1400 Node item = list.item(0);
1401 if (item instanceof Element) {
1402 // Handle different color spaces (tested with RGB and grayscale)
1403 String value = ((Element)item).getAttribute("value");
1404 if (!value.isEmpty()) {
1405 String[] s = value.split(" ");
1406 if (s.length == 3) {
1407 return parseRGB(s);
1408 } else if (s.length == 1) {
1409 int pixel = Integer.parseInt(s[0]);
1410 int r = model.getRed(pixel);
1411 int g = model.getGreen(pixel);
1412 int b = model.getBlue(pixel);
1413 return new Color(r,g,b);
1414 } else {
1415 Main.warn("Unable to translate TransparentColor '"+value+"' with color model "+model);
1416 }
1417 }
1418 }
1419 }
1420 }
1421 break;
1422 }
1423 }
1424 }
1425 }
1426 } catch (IIOException | NumberFormatException e) {
1427 // JAI doesn't like some JPEG files with error "Inconsistent metadata read from stream" (see #10267)
1428 Main.warn(e);
1429 }
1430 return null;
1431 }
1432
1433 private static Color parseRGB(String[] s) {
1434 int[] rgb = new int[3];
1435 try {
1436 for (int i = 0; i<3; i++) {
1437 rgb[i] = Integer.parseInt(s[i]);
1438 }
1439 return new Color(rgb[0], rgb[1], rgb[2]);
1440 } catch (IllegalArgumentException e) {
1441 Main.error(e);
1442 return null;
1443 }
1444 }
1445
1446 /**
1447 * Returns a transparent version of the given image, based on the given transparent color.
1448 * @param bi The image to convert
1449 * @param color The transparent color
1450 * @return The same image as {@code bi} where all pixels of the given color are transparent.
1451 * This resulting image has also the special property {@link #PROP_TRANSPARENCY_FORCED} set to {@code color}
1452 * @since 7132
1453 * @see BufferedImage#getProperty
1454 * @see #isTransparencyForced
1455 */
1456 public static BufferedImage makeImageTransparent(BufferedImage bi, Color color) {
1457 // the color we are looking for. Alpha bits are set to opaque
1458 final int markerRGB = color.getRGB() | 0xFF000000;
1459 ImageFilter filter = new RGBImageFilter() {
1460 @Override
1461 public int filterRGB(int x, int y, int rgb) {
1462 if ((rgb | 0xFF000000) == markerRGB) {
1463 // Mark the alpha bits as zero - transparent
1464 return 0x00FFFFFF & rgb;
1465 } else {
1466 return rgb;
1467 }
1468 }
1469 };
1470 ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
1471 Image img = Toolkit.getDefaultToolkit().createImage(ip);
1472 ColorModel colorModel = ColorModel.getRGBdefault();
1473 WritableRaster raster = colorModel.createCompatibleWritableRaster(img.getWidth(null), img.getHeight(null));
1474 String[] names = bi.getPropertyNames();
1475 Hashtable<String, Object> properties = new Hashtable<>(1 + (names != null ? names.length : 0));
1476 if (names != null) {
1477 for (String name : names) {
1478 properties.put(name, bi.getProperty(name));
1479 }
1480 }
1481 properties.put(PROP_TRANSPARENCY_FORCED, Boolean.TRUE);
1482 BufferedImage result = new BufferedImage(colorModel, raster, false, properties);
1483 Graphics2D g2 = result.createGraphics();
1484 g2.drawImage(img, 0, 0, null);
1485 g2.dispose();
1486 return result;
1487 }
1488
1489 /**
1490 * Determines if the transparency of the given {@code BufferedImage} has been enforced by a previous call to {@link #makeImageTransparent}.
1491 * @param bi The {@code BufferedImage} to test
1492 * @return {@code true} if the transparency of {@code bi} has been enforced by a previous call to {@code makeImageTransparent}.
1493 * @since 7132
1494 * @see #makeImageTransparent
1495 */
1496 public static boolean isTransparencyForced(BufferedImage bi) {
1497 return bi != null && !bi.getProperty(PROP_TRANSPARENCY_FORCED).equals(Image.UndefinedProperty);
1498 }
1499
1500 /**
1501 * Determines if the given {@code BufferedImage} has a transparent color determiend by a previous call to {@link #read}.
1502 * @param bi The {@code BufferedImage} to test
1503 * @return {@code true} if {@code bi} has a transparent color determined by a previous call to {@code read}.
1504 * @since 7132
1505 * @see #read
1506 */
1507 public static boolean hasTransparentColor(BufferedImage bi) {
1508 return bi != null && !bi.getProperty(PROP_TRANSPARENCY_COLOR).equals(Image.UndefinedProperty);
1509 }
1510}
Note: See TracBrowser for help on using the repository browser.