001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Color;
007import java.awt.Cursor;
008import java.awt.Dimension;
009import java.awt.Graphics;
010import java.awt.Graphics2D;
011import java.awt.GraphicsEnvironment;
012import java.awt.Image;
013import java.awt.Point;
014import java.awt.RenderingHints;
015import java.awt.Toolkit;
016import java.awt.Transparency;
017import java.awt.image.BufferedImage;
018import java.awt.image.ColorModel;
019import java.awt.image.FilteredImageSource;
020import java.awt.image.ImageFilter;
021import java.awt.image.ImageProducer;
022import java.awt.image.RGBImageFilter;
023import java.awt.image.WritableRaster;
024import java.io.ByteArrayInputStream;
025import java.io.File;
026import java.io.IOException;
027import java.io.InputStream;
028import java.io.StringReader;
029import java.io.UnsupportedEncodingException;
030import java.net.URI;
031import java.net.URL;
032import java.net.URLDecoder;
033import java.net.URLEncoder;
034import java.nio.charset.StandardCharsets;
035import java.util.ArrayList;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.HashMap;
039import java.util.Hashtable;
040import java.util.Iterator;
041import java.util.Map;
042import java.util.concurrent.ExecutorService;
043import java.util.concurrent.Executors;
044import java.util.regex.Matcher;
045import java.util.regex.Pattern;
046import java.util.zip.ZipEntry;
047import java.util.zip.ZipFile;
048
049import javax.imageio.IIOException;
050import javax.imageio.ImageIO;
051import javax.imageio.ImageReadParam;
052import javax.imageio.ImageReader;
053import javax.imageio.metadata.IIOMetadata;
054import javax.imageio.stream.ImageInputStream;
055import javax.swing.Icon;
056import javax.swing.ImageIcon;
057
058import org.apache.commons.codec.binary.Base64;
059import org.openstreetmap.josm.Main;
060import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
061import org.openstreetmap.josm.io.CachedFile;
062import org.openstreetmap.josm.plugins.PluginHandler;
063import org.w3c.dom.Element;
064import org.w3c.dom.Node;
065import org.w3c.dom.NodeList;
066import org.xml.sax.Attributes;
067import org.xml.sax.EntityResolver;
068import org.xml.sax.InputSource;
069import org.xml.sax.SAXException;
070import org.xml.sax.XMLReader;
071import org.xml.sax.helpers.DefaultHandler;
072import org.xml.sax.helpers.XMLReaderFactory;
073
074import com.kitfox.svg.SVGDiagram;
075import com.kitfox.svg.SVGException;
076import com.kitfox.svg.SVGUniverse;
077
078/**
079 * Helper class to support the application with images.
080 *
081 * How to use:
082 *
083 * <code>ImageIcon icon = new ImageProvider(name).setMaxWidth(24).setMaxHeight(24).get();</code>
084 * (there are more options, see below)
085 *
086 * short form:
087 * <code>ImageIcon icon = ImageProvider.get(name);</code>
088 *
089 * @author imi
090 */
091public class ImageProvider {
092
093    /**
094     * Position of an overlay icon
095     */
096    public static enum OverlayPosition {
097        NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST
098    }
099
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                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            CachedFile cf = new CachedFile(base + fn).setDestDir(new File(Main.pref.getPreferencesDir(), "images").toString());
803            try (InputStream is = cf.getInputStream()) {
804                parser.parse(new InputSource(is));
805            }
806        } catch (SAXReturnException r) {
807            return r.getResult();
808        } catch (Exception e) {
809            Main.warn("Parsing " + base + fn + " failed:\n" + e);
810            return null;
811        }
812        Main.warn("Parsing " + base + fn + " failed: Unexpected content.");
813        return null;
814    }
815
816    public static Cursor getCursor(String name, String overlay) {
817        ImageIcon img = get("cursor", name);
818        if (overlay != null) {
819            img = overlay(img, ImageProvider.get("cursor/modifier/" + overlay), OverlayPosition.SOUTHEAST);
820        }
821        if (GraphicsEnvironment.isHeadless()) {
822            Main.warn("Cursors are not available in headless mode. Returning null for '"+name+"'");
823            return null;
824        }
825        return Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
826                "crosshair".equals(name) ? new Point(10, 10) : new Point(3, 2), "Cursor");
827    }
828
829    /**
830     * Decorate one icon with an overlay icon.
831     *
832     * @param ground the base image
833     * @param overlay the overlay image (can be smaller than the base image)
834     * @param pos position of the overlay image inside the base image (positioned
835     * in one of the corners)
836     * @return an icon that represent the overlay of the two given icons. The second icon is layed
837     * on the first relative to the given position.
838     */
839    public static ImageIcon overlay(Icon ground, Icon overlay, OverlayPosition pos) {
840        int w = ground.getIconWidth();
841        int h = ground.getIconHeight();
842        int wo = overlay.getIconWidth();
843        int ho = overlay.getIconHeight();
844        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
845        Graphics g = img.createGraphics();
846        ground.paintIcon(null, g, 0, 0);
847        int x = 0, y = 0;
848        switch (pos) {
849        case NORTHWEST:
850            x = 0;
851            y = 0;
852            break;
853        case NORTHEAST:
854            x = w - wo;
855            y = 0;
856            break;
857        case SOUTHWEST:
858            x = 0;
859            y = h - ho;
860            break;
861        case SOUTHEAST:
862            x = w - wo;
863            y = h - ho;
864            break;
865        }
866        overlay.paintIcon(null, g, x, y);
867        return new ImageIcon(img);
868    }
869
870    /** 90 degrees in radians units */
871    static final double DEGREE_90 = 90.0 * Math.PI / 180.0;
872
873    /**
874     * Creates a rotated version of the input image.
875     *
876     * @param img the image to be rotated.
877     * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
878     * will mod it with 360 before using it. More over for caching performance, it will be rounded to
879     * an entire value between 0 and 360.
880     *
881     * @return the image after rotating.
882     * @since 6172
883     */
884    public static Image createRotatedImage(Image img, double rotatedAngle) {
885        return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
886    }
887
888    /**
889     * Creates a rotated version of the input image, scaled to the given dimension.
890     *
891     * @param img the image to be rotated.
892     * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
893     * will mod it with 360 before using it. More over for caching performance, it will be rounded to
894     * an entire value between 0 and 360.
895     * @param dimension The requested dimensions. Use (-1,-1) for the original size
896     * and (width, -1) to set the width, but otherwise scale the image proportionally.
897     * @return the image after rotating and scaling.
898     * @since 6172
899     */
900    public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
901        CheckParameterUtil.ensureParameterNotNull(img, "img");
902
903        // convert rotatedAngle to an integer value from 0 to 360
904        Long originalAngle = Math.round(rotatedAngle % 360);
905        if (rotatedAngle != 0 && originalAngle == 0) {
906            originalAngle = 360L;
907        }
908
909        ImageResource imageResource = null;
910
911        synchronized (ROTATE_CACHE) {
912            Map<Long, ImageResource> cacheByAngle = ROTATE_CACHE.get(img);
913            if (cacheByAngle == null) {
914                ROTATE_CACHE.put(img, cacheByAngle = new HashMap<>());
915            }
916
917            imageResource = cacheByAngle.get(originalAngle);
918
919            if (imageResource == null) {
920                // convert originalAngle to a value from 0 to 90
921                double angle = originalAngle % 90;
922                if (originalAngle != 0.0 && angle == 0.0) {
923                    angle = 90.0;
924                }
925
926                double radian = Math.toRadians(angle);
927
928                new ImageIcon(img); // load completely
929                int iw = img.getWidth(null);
930                int ih = img.getHeight(null);
931                int w;
932                int h;
933
934                if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
935                    w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
936                    h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
937                } else {
938                    w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
939                    h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
940                }
941                Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
942                cacheByAngle.put(originalAngle, imageResource = new ImageResource(image));
943                Graphics g = image.getGraphics();
944                Graphics2D g2d = (Graphics2D) g.create();
945
946                // calculate the center of the icon.
947                int cx = iw / 2;
948                int cy = ih / 2;
949
950                // move the graphics center point to the center of the icon.
951                g2d.translate(w / 2, h / 2);
952
953                // rotate the graphics about the center point of the icon
954                g2d.rotate(Math.toRadians(originalAngle));
955
956                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
957                g2d.drawImage(img, -cx, -cy, null);
958
959                g2d.dispose();
960                new ImageIcon(image); // load completely
961            }
962            return imageResource.getImageIcon(dimension).getImage();
963        }
964    }
965
966    /**
967     * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
968     *
969     * @param img the image to be scaled down.
970     * @param maxSize the maximum size in pixels (both for width and height)
971     *
972     * @return the image after scaling.
973     * @since 6172
974     */
975    public static Image createBoundedImage(Image img, int maxSize) {
976        return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
977    }
978
979    /**
980     * Replies the icon for an OSM primitive type
981     * @param type the type
982     * @return the icon
983     */
984    public static ImageIcon get(OsmPrimitiveType type) {
985        CheckParameterUtil.ensureParameterNotNull(type, "type");
986        return get("data", type.getAPIName());
987    }
988
989    public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
990        float realWidth = svg.getWidth();
991        float realHeight = svg.getHeight();
992        int width = Math.round(realWidth);
993        int height = Math.round(realHeight);
994        Double scaleX = null, scaleY = null;
995        if (dim.width != -1) {
996            width = dim.width;
997            scaleX = (double) width / realWidth;
998            if (dim.height == -1) {
999                scaleY = scaleX;
1000                height = (int) Math.round(realHeight * scaleY);
1001            } else {
1002                height = dim.height;
1003                scaleY = (double) height / realHeight;
1004            }
1005        } else if (dim.height != -1) {
1006            height = dim.height;
1007            scaleX = scaleY = (double) height / realHeight;
1008            width = (int) Math.round(realWidth * scaleX);
1009        }
1010        if (width == 0 || height == 0) {
1011            return null;
1012        }
1013        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
1014        Graphics2D g = img.createGraphics();
1015        g.setClip(0, 0, width, height);
1016        if (scaleX != null && scaleY != null) {
1017            g.scale(scaleX, scaleY);
1018        }
1019        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
1020        try {
1021            svg.render(g);
1022        } catch (SVGException ex) {
1023            return null;
1024        }
1025        return img;
1026    }
1027
1028    private static SVGUniverse getSvgUniverse() {
1029        if (svgUniverse == null) {
1030            svgUniverse = new SVGUniverse();
1031        }
1032        return svgUniverse;
1033    }
1034
1035    /**
1036     * Returns a <code>BufferedImage</code> as the result of decoding
1037     * a supplied <code>File</code> with an <code>ImageReader</code>
1038     * chosen automatically from among those currently registered.
1039     * The <code>File</code> is wrapped in an
1040     * <code>ImageInputStream</code>.  If no registered
1041     * <code>ImageReader</code> claims to be able to read the
1042     * resulting stream, <code>null</code> is returned.
1043     *
1044     * <p> The current cache settings from <code>getUseCache</code>and
1045     * <code>getCacheDirectory</code> will be used to control caching in the
1046     * <code>ImageInputStream</code> that is created.
1047     *
1048     * <p> Note that there is no <code>read</code> method that takes a
1049     * filename as a <code>String</code>; use this method instead after
1050     * creating a <code>File</code> from the filename.
1051     *
1052     * <p> This method does not attempt to locate
1053     * <code>ImageReader</code>s that can read directly from a
1054     * <code>File</code>; that may be accomplished using
1055     * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1056     *
1057     * @param input a <code>File</code> to read from.
1058     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color, if any.
1059     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1060     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1061     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1062     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1063     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1064     *
1065     * @return a <code>BufferedImage</code> containing the decoded
1066     * contents of the input, or <code>null</code>.
1067     *
1068     * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1069     * @throws IOException if an error occurs during reading.
1070     * @since 7132
1071     * @see BufferedImage#getProperty
1072     */
1073    public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1074        CheckParameterUtil.ensureParameterNotNull(input, "input");
1075        if (!input.canRead()) {
1076            throw new IIOException("Can't read input file!");
1077        }
1078
1079        ImageInputStream stream = ImageIO.createImageInputStream(input);
1080        if (stream == null) {
1081            throw new IIOException("Can't create an ImageInputStream!");
1082        }
1083        BufferedImage bi = read(stream, readMetadata, enforceTransparency);
1084        if (bi == null) {
1085            stream.close();
1086        }
1087        return bi;
1088    }
1089
1090    /**
1091     * Returns a <code>BufferedImage</code> as the result of decoding
1092     * a supplied <code>InputStream</code> with an <code>ImageReader</code>
1093     * chosen automatically from among those currently registered.
1094     * The <code>InputStream</code> is wrapped in an
1095     * <code>ImageInputStream</code>.  If no registered
1096     * <code>ImageReader</code> claims to be able to read the
1097     * resulting stream, <code>null</code> is returned.
1098     *
1099     * <p> The current cache settings from <code>getUseCache</code>and
1100     * <code>getCacheDirectory</code> will be used to control caching in the
1101     * <code>ImageInputStream</code> that is created.
1102     *
1103     * <p> This method does not attempt to locate
1104     * <code>ImageReader</code>s that can read directly from an
1105     * <code>InputStream</code>; that may be accomplished using
1106     * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1107     *
1108     * <p> This method <em>does not</em> close the provided
1109     * <code>InputStream</code> after the read operation has completed;
1110     * it is the responsibility of the caller to close the stream, if desired.
1111     *
1112     * @param input an <code>InputStream</code> to read from.
1113     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1114     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1115     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1116     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1117     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1118     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1119     *
1120     * @return a <code>BufferedImage</code> containing the decoded
1121     * contents of the input, or <code>null</code>.
1122     *
1123     * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1124     * @throws IOException if an error occurs during reading.
1125     * @since 7132
1126     */
1127    public static BufferedImage read(InputStream input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1128        CheckParameterUtil.ensureParameterNotNull(input, "input");
1129
1130        ImageInputStream stream = ImageIO.createImageInputStream(input);
1131        BufferedImage bi = read(stream, readMetadata, enforceTransparency);
1132        if (bi == null) {
1133            stream.close();
1134        }
1135        return bi;
1136    }
1137
1138    /**
1139     * Returns a <code>BufferedImage</code> as the result of decoding
1140     * a supplied <code>URL</code> with an <code>ImageReader</code>
1141     * chosen automatically from among those currently registered.  An
1142     * <code>InputStream</code> is obtained from the <code>URL</code>,
1143     * which is wrapped in an <code>ImageInputStream</code>.  If no
1144     * registered <code>ImageReader</code> claims to be able to read
1145     * the resulting stream, <code>null</code> is returned.
1146     *
1147     * <p> The current cache settings from <code>getUseCache</code>and
1148     * <code>getCacheDirectory</code> will be used to control caching in the
1149     * <code>ImageInputStream</code> that is created.
1150     *
1151     * <p> This method does not attempt to locate
1152     * <code>ImageReader</code>s that can read directly from a
1153     * <code>URL</code>; that may be accomplished using
1154     * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1155     *
1156     * @param input a <code>URL</code> to read from.
1157     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1158     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1159     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1160     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1161     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1162     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1163     *
1164     * @return a <code>BufferedImage</code> containing the decoded
1165     * contents of the input, or <code>null</code>.
1166     *
1167     * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1168     * @throws IOException if an error occurs during reading.
1169     * @since 7132
1170     */
1171    public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1172        CheckParameterUtil.ensureParameterNotNull(input, "input");
1173
1174        InputStream istream = null;
1175        try {
1176            istream = input.openStream();
1177        } catch (IOException e) {
1178            throw new IIOException("Can't get input stream from URL!", e);
1179        }
1180        ImageInputStream stream = ImageIO.createImageInputStream(istream);
1181        BufferedImage bi;
1182        try {
1183            bi = read(stream, readMetadata, enforceTransparency);
1184            if (bi == null) {
1185                stream.close();
1186            }
1187        } finally {
1188            istream.close();
1189        }
1190        return bi;
1191    }
1192
1193    /**
1194     * Returns a <code>BufferedImage</code> as the result of decoding
1195     * a supplied <code>ImageInputStream</code> with an
1196     * <code>ImageReader</code> chosen automatically from among those
1197     * currently registered.  If no registered
1198     * <code>ImageReader</code> claims to be able to read the stream,
1199     * <code>null</code> is returned.
1200     *
1201     * <p> Unlike most other methods in this class, this method <em>does</em>
1202     * close the provided <code>ImageInputStream</code> after the read
1203     * operation has completed, unless <code>null</code> is returned,
1204     * in which case this method <em>does not</em> close the stream.
1205     *
1206     * @param stream an <code>ImageInputStream</code> to read from.
1207     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1208     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1209     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1210     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1211     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1212     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1213     *
1214     * @return a <code>BufferedImage</code> containing the decoded
1215     * contents of the input, or <code>null</code>.
1216     *
1217     * @throws IllegalArgumentException if <code>stream</code> is <code>null</code>.
1218     * @throws IOException if an error occurs during reading.
1219     * @since 7132
1220     */
1221    public static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency) throws IOException {
1222        CheckParameterUtil.ensureParameterNotNull(stream, "stream");
1223
1224        Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
1225        if (!iter.hasNext()) {
1226            return null;
1227        }
1228
1229        ImageReader reader = iter.next();
1230        ImageReadParam param = reader.getDefaultReadParam();
1231        reader.setInput(stream, true, !readMetadata && !enforceTransparency);
1232        BufferedImage bi;
1233        try {
1234            bi = reader.read(0, param);
1235            if (bi.getTransparency() != Transparency.TRANSLUCENT && (readMetadata || enforceTransparency)) {
1236                Color color = getTransparentColor(reader);
1237                if (color != null) {
1238                    Hashtable<String, Object> properties = new Hashtable<>(1);
1239                    properties.put(PROP_TRANSPARENCY_COLOR, color);
1240                    bi = new BufferedImage(bi.getColorModel(), bi.getRaster(), bi.isAlphaPremultiplied(), properties);
1241                    if (enforceTransparency) {
1242                        if (Main.isDebugEnabled()) {
1243                            Main.debug("Enforcing image transparency of "+stream+" for "+color);
1244                        }
1245                        bi = makeImageTransparent(bi, color);
1246                    }
1247                }
1248            }
1249        } finally {
1250            reader.dispose();
1251            stream.close();
1252        }
1253        return bi;
1254    }
1255
1256    /**
1257     * Returns the {@code TransparentColor} defined in image reader metadata.
1258     * @param reader The image reader
1259     * @return the {@code TransparentColor} defined in image reader metadata, or {@code null}
1260     * @throws IOException if an error occurs during reading
1261     * @since 7132
1262     * @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>
1263     */
1264    public static Color getTransparentColor(ImageReader reader) throws IOException {
1265        try {
1266            IIOMetadata metadata = reader.getImageMetadata(0);
1267            if (metadata != null) {
1268                String[] formats = metadata.getMetadataFormatNames();
1269                if (formats != null) {
1270                    for (String f : formats) {
1271                        if ("javax_imageio_1.0".equals(f)) {
1272                            Node root = metadata.getAsTree(f);
1273                            if (root instanceof Element) {
1274                                NodeList list = ((Element)root).getElementsByTagName("TransparentColor");
1275                                if (list.getLength() > 0) {
1276                                    Node item = list.item(0);
1277                                    if (item instanceof Element) {
1278                                        String[] s = ((Element)item).getAttribute("value").split(" ");
1279                                        if (s.length == 3) {
1280                                            return parseRGB(s);
1281                                        }
1282                                    }
1283                                }
1284                            }
1285                            break;
1286                        }
1287                    }
1288                }
1289            }
1290        } catch (IIOException e) {
1291            // JAI doesn't like some JPEG files with error "Inconsistent metadata read from stream" (see #10267)
1292            Main.warn(e);
1293        }
1294        return null;
1295    }
1296
1297    private static Color parseRGB(String[] s) {
1298        int[] rgb = new int[3];
1299        try {
1300            for (int i = 0; i<3; i++) {
1301                rgb[i] = Integer.parseInt(s[i]);
1302            }
1303            return new Color(rgb[0], rgb[1], rgb[2]);
1304        } catch (IllegalArgumentException e) {
1305            Main.error(e);
1306            return null;
1307        }
1308    }
1309
1310    /**
1311     * Returns a transparent version of the given image, based on the given transparent color.
1312     * @param bi The image to convert
1313     * @param color The transparent color
1314     * @return The same image as {@code bi} where all pixels of the given color are transparent.
1315     * This resulting image has also the special property {@link #PROP_TRANSPARENCY_FORCED} set to {@code color}
1316     * @since 7132
1317     * @see BufferedImage#getProperty
1318     * @see #isTransparencyForced
1319     */
1320    public static BufferedImage makeImageTransparent(BufferedImage bi, Color color) {
1321        // the color we are looking for. Alpha bits are set to opaque
1322        final int markerRGB = color.getRGB() | 0xFFFFFFFF;
1323        ImageFilter filter = new RGBImageFilter() {
1324            @Override
1325            public int filterRGB(int x, int y, int rgb) {
1326                if ((rgb | 0xFF000000) == markerRGB) {
1327                   // Mark the alpha bits as zero - transparent
1328                   return 0x00FFFFFF & rgb;
1329                } else {
1330                   return rgb;
1331                }
1332            }
1333        };
1334        ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
1335        Image img = Toolkit.getDefaultToolkit().createImage(ip);
1336        ColorModel colorModel = ColorModel.getRGBdefault();
1337        WritableRaster raster = colorModel.createCompatibleWritableRaster(img.getWidth(null), img.getHeight(null));
1338        String[] names = bi.getPropertyNames();
1339        Hashtable<String, Object> properties = new Hashtable<>(1 + (names != null ? names.length : 0));
1340        if (names != null) {
1341            for (String name : names) {
1342                properties.put(name, bi.getProperty(name));
1343            }
1344        }
1345        properties.put(PROP_TRANSPARENCY_FORCED, Boolean.TRUE);
1346        BufferedImage result = new BufferedImage(colorModel, raster, false, properties);
1347        Graphics2D g2 = result.createGraphics();
1348        g2.drawImage(img, 0, 0, null);
1349        g2.dispose();
1350        return result;
1351    }
1352
1353    /**
1354     * Determines if the transparency of the given {@code BufferedImage} has been enforced by a previous call to {@link #makeImageTransparent}.
1355     * @param bi The {@code BufferedImage} to test
1356     * @return {@code true} if the transparency of {@code bi} has been enforced by a previous call to {@code makeImageTransparent}.
1357     * @since 7132
1358     * @see #makeImageTransparent
1359     */
1360    public static boolean isTransparencyForced(BufferedImage bi) {
1361        return bi != null && !bi.getProperty(PROP_TRANSPARENCY_FORCED).equals(Image.UndefinedProperty);
1362    }
1363
1364    /**
1365     * Determines if the given {@code BufferedImage} has a transparent color determiend by a previous call to {@link #read}.
1366     * @param bi The {@code BufferedImage} to test
1367     * @return {@code true} if {@code bi} has a transparent color determined by a previous call to {@code read}.
1368     * @since 7132
1369     * @see #read
1370     */
1371    public static boolean hasTransparentColor(BufferedImage bi) {
1372        return bi != null && !bi.getProperty(PROP_TRANSPARENCY_COLOR).equals(Image.UndefinedProperty);
1373    }
1374}