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

Last change on this file since 7193 was 7134, checked in by Don-vip, 10 years ago

fix #10030 - wms support broken in r7132

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