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

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

see #10684 - no double loading of images, cleanup action icons - menu icon size defaults now to 16x16 (previously most time 24x24) with some errors - maybe 24x24 should be default?

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