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

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

fix #10479 - proper handling of transparent files

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