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

Last change on this file since 6797 was 6747, checked in by bastiK, 10 years ago

#8581 - Embedded SVG leads to very high memory consumption

  • Property svn:eol-style set to native
File size: 35.2 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.Cursor;
7import java.awt.Dimension;
8import java.awt.Graphics;
9import java.awt.Graphics2D;
10import java.awt.GraphicsConfiguration;
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.io.ByteArrayInputStream;
19import java.io.File;
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.StringReader;
23import java.io.UnsupportedEncodingException;
24import java.net.MalformedURLException;
25import java.net.URI;
26import java.net.URL;
27import java.net.URLDecoder;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.HashMap;
32import java.util.Map;
33import java.util.concurrent.ExecutorService;
34import java.util.concurrent.Executors;
35import java.util.regex.Matcher;
36import java.util.regex.Pattern;
37import java.util.zip.ZipEntry;
38import java.util.zip.ZipFile;
39
40import javax.imageio.ImageIO;
41import javax.swing.Icon;
42import javax.swing.ImageIcon;
43
44import org.apache.commons.codec.binary.Base64;
45import org.openstreetmap.josm.Main;
46import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
47import org.openstreetmap.josm.io.MirroredInputStream;
48import org.openstreetmap.josm.plugins.PluginHandler;
49import org.xml.sax.Attributes;
50import org.xml.sax.EntityResolver;
51import org.xml.sax.InputSource;
52import org.xml.sax.SAXException;
53import org.xml.sax.XMLReader;
54import org.xml.sax.helpers.DefaultHandler;
55import org.xml.sax.helpers.XMLReaderFactory;
56
57import com.kitfox.svg.SVGDiagram;
58import com.kitfox.svg.SVGException;
59import com.kitfox.svg.SVGUniverse;
60
61/**
62 * Helper class to support the application with images.
63 *
64 * How to use:
65 *
66 * <code>ImageIcon icon = new ImageProvider(name).setMaxWidth(24).setMaxHeight(24).get();</code>
67 * (there are more options, see below)
68 *
69 * short form:
70 * <code>ImageIcon icon = ImageProvider.get(name);</code>
71 *
72 * @author imi
73 */
74public class ImageProvider {
75
76 /**
77 * Position of an overlay icon
78 * @author imi
79 */
80 public static enum OverlayPosition {
81 NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST
82 }
83
84 /**
85 * Supported image types
86 */
87 public static enum ImageType {
88 /** Scalable vector graphics */
89 SVG,
90 /** Everything else, e.g. png, gif (must be supported by Java) */
91 OTHER
92 }
93
94 protected Collection<String> dirs;
95 protected String id;
96 protected String subdir;
97 protected String name;
98 protected File archive;
99 protected String inArchiveDir;
100 protected int width = -1;
101 protected int height = -1;
102 protected int maxWidth = -1;
103 protected int maxHeight = -1;
104 protected boolean optional;
105 protected boolean suppressWarnings;
106 protected Collection<ClassLoader> additionalClassLoaders;
107
108 private static SVGUniverse svgUniverse;
109
110 /**
111 * The icon cache
112 */
113 private static final Map<String, ImageResource> cache = new HashMap<String, ImageResource>();
114
115 /**
116 * Caches the image data for rotated versions of the same image.
117 */
118 private static final Map<Image, Map<Long, ImageResource>> ROTATE_CACHE = new HashMap<Image, Map<Long, ImageResource>>();
119
120 private static final ExecutorService IMAGE_FETCHER = Executors.newSingleThreadExecutor();
121
122 public interface ImageCallback {
123 void finished(ImageIcon result);
124 }
125
126 /**
127 * Constructs a new {@code ImageProvider} from a filename in a given directory.
128 * @param subdir subdirectory the image lies in
129 * @param name the name of the image. If it does not end with '.png' or '.svg',
130 * both extensions are tried.
131 */
132 public ImageProvider(String subdir, String name) {
133 this.subdir = subdir;
134 this.name = name;
135 }
136
137 /**
138 * Constructs a new {@code ImageProvider} from a filename.
139 * @param name the name of the image. If it does not end with '.png' or '.svg',
140 * both extensions are tried.
141 */
142 public ImageProvider(String name) {
143 this.name = name;
144 }
145
146 /**
147 * Directories to look for the image.
148 * @param dirs The directories to look for.
149 * @return the current object, for convenience
150 */
151 public ImageProvider setDirs(Collection<String> dirs) {
152 this.dirs = dirs;
153 return this;
154 }
155
156 /**
157 * Set an id used for caching.
158 * If name starts with <tt>http://</tt> Id is not used for the cache.
159 * (A URL is unique anyway.)
160 * @return the current object, for convenience
161 */
162 public ImageProvider setId(String id) {
163 this.id = id;
164 return this;
165 }
166
167 /**
168 * Specify a zip file where the image is located.
169 *
170 * (optional)
171 * @return the current object, for convenience
172 */
173 public ImageProvider setArchive(File archive) {
174 this.archive = archive;
175 return this;
176 }
177
178 /**
179 * Specify a base path inside the zip file.
180 *
181 * The subdir and name will be relative to this path.
182 *
183 * (optional)
184 * @return the current object, for convenience
185 */
186 public ImageProvider setInArchiveDir(String inArchiveDir) {
187 this.inArchiveDir = inArchiveDir;
188 return this;
189 }
190
191 /**
192 * Set the dimensions of the image.
193 *
194 * If not specified, the original size of the image is used.
195 * The width part of the dimension can be -1. Then it will only set the height but
196 * keep the aspect ratio. (And the other way around.)
197 * @return the current object, for convenience
198 */
199 public ImageProvider setSize(Dimension size) {
200 this.width = size.width;
201 this.height = size.height;
202 return this;
203 }
204
205 /**
206 * @see #setSize
207 * @return the current object, for convenience
208 */
209 public ImageProvider setWidth(int width) {
210 this.width = width;
211 return this;
212 }
213
214 /**
215 * @see #setSize
216 * @return the current object, for convenience
217 */
218 public ImageProvider setHeight(int height) {
219 this.height = height;
220 return this;
221 }
222
223 /**
224 * Limit the maximum size of the image.
225 *
226 * It will shrink the image if necessary, but keep the aspect ratio.
227 * The given width or height can be -1 which means this direction is not bounded.
228 *
229 * 'size' and 'maxSize' are not compatible, you should set only one of them.
230 * @return the current object, for convenience
231 */
232 public ImageProvider setMaxSize(Dimension maxSize) {
233 this.maxWidth = maxSize.width;
234 this.maxHeight = maxSize.height;
235 return this;
236 }
237
238 /**
239 * Convenience method, see {@link #setMaxSize(Dimension)}.
240 * @return the current object, for convenience
241 */
242 public ImageProvider setMaxSize(int maxSize) {
243 return this.setMaxSize(new Dimension(maxSize, maxSize));
244 }
245
246 /**
247 * @see #setMaxSize
248 * @return the current object, for convenience
249 */
250 public ImageProvider setMaxWidth(int maxWidth) {
251 this.maxWidth = maxWidth;
252 return this;
253 }
254
255 /**
256 * @see #setMaxSize
257 * @return the current object, for convenience
258 */
259 public ImageProvider setMaxHeight(int maxHeight) {
260 this.maxHeight = maxHeight;
261 return this;
262 }
263
264 /**
265 * Decide, if an exception should be thrown, when the image cannot be located.
266 *
267 * Set to true, when the image URL comes from user data and the image may be missing.
268 *
269 * @param optional true, if JOSM should <b>not</b> throw a RuntimeException
270 * in case the image cannot be located.
271 * @return the current object, for convenience
272 */
273 public ImageProvider setOptional(boolean optional) {
274 this.optional = optional;
275 return this;
276 }
277
278 /**
279 * Suppresses warning on the command line in case the image cannot be found.
280 *
281 * In combination with setOptional(true);
282 * @return the current object, for convenience
283 */
284 public ImageProvider setSuppressWarnings(boolean suppressWarnings) {
285 this.suppressWarnings = suppressWarnings;
286 return this;
287 }
288
289 /**
290 * Add a collection of additional class loaders to search image for.
291 * @return the current object, for convenience
292 */
293 public ImageProvider setAdditionalClassLoaders(Collection<ClassLoader> additionalClassLoaders) {
294 this.additionalClassLoaders = additionalClassLoaders;
295 return this;
296 }
297
298 /**
299 * Execute the image request.
300 * @return the requested image or null if the request failed
301 */
302 public ImageIcon get() {
303 ImageResource ir = getIfAvailableImpl(additionalClassLoaders);
304 if (ir == null) {
305 if (!optional) {
306 String ext = name.indexOf('.') != -1 ? "" : ".???";
307 throw new RuntimeException(tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.", name + ext));
308 } else {
309 if (!suppressWarnings) {
310 Main.error(tr("Failed to locate image ''{0}''", name));
311 }
312 return null;
313 }
314 }
315 if (maxWidth != -1 || maxHeight != -1)
316 return ir.getImageIconBounded(new Dimension(maxWidth, maxHeight));
317 else
318 return ir.getImageIcon(new Dimension(width, height));
319 }
320
321 /**
322 * Load the image in a background thread.
323 *
324 * This method returns immediately and runs the image request
325 * asynchronously.
326 *
327 * @param callback a callback. It is called, when the image is ready.
328 * This can happen before the call to this method returns or it may be
329 * invoked some time (seconds) later. If no image is available, a null
330 * value is returned to callback (just like {@link #get}).
331 */
332 public void getInBackground(final ImageCallback callback) {
333 if (name.startsWith("http://") || name.startsWith("wiki://")) {
334 Runnable fetch = new Runnable() {
335 @Override
336 public void run() {
337 ImageIcon result = get();
338 callback.finished(result);
339 }
340 };
341 IMAGE_FETCHER.submit(fetch);
342 } else {
343 ImageIcon result = get();
344 callback.finished(result);
345 }
346 }
347
348 /**
349 * Load an image with a given file name.
350 *
351 * @param subdir subdirectory the image lies in
352 * @param name The icon name (base name with or without '.png' or '.svg' extension)
353 * @return The requested Image.
354 * @throws RuntimeException if the image cannot be located
355 */
356 public static ImageIcon get(String subdir, String name) {
357 return new ImageProvider(subdir, name).get();
358 }
359
360 /**
361 * @see #get(java.lang.String, java.lang.String)
362 */
363 public static ImageIcon get(String name) {
364 return new ImageProvider(name).get();
365 }
366
367 /**
368 * Load an image with a given file name, but do not throw an exception
369 * when the image cannot be found.
370 * @see #get(java.lang.String, java.lang.String)
371 */
372 public static ImageIcon getIfAvailable(String subdir, String name) {
373 return new ImageProvider(subdir, name).setOptional(true).get();
374 }
375
376 /**
377 * @see #getIfAvailable(java.lang.String, java.lang.String)
378 */
379 public static ImageIcon getIfAvailable(String name) {
380 return new ImageProvider(name).setOptional(true).get();
381 }
382
383 /**
384 * {@code data:[<mediatype>][;base64],<data>}
385 * @see <a href="http://tools.ietf.org/html/rfc2397">RFC2397</a>
386 */
387 private static final Pattern dataUrlPattern = Pattern.compile(
388 "^data:([a-zA-Z]+/[a-zA-Z+]+)?(;base64)?,(.+)$");
389
390 private ImageResource getIfAvailableImpl(Collection<ClassLoader> additionalClassLoaders) {
391 synchronized (cache) {
392 // This method is called from different thread and modifying HashMap concurrently can result
393 // for example in loops in map entries (ie freeze when such entry is retrieved)
394 // Yes, it did happen to me :-)
395 if (name == null)
396 return null;
397
398 if (name.startsWith("data:")) {
399 String url = name;
400 ImageResource ir = cache.get(url);
401 if (ir != null) return ir;
402 ir = getIfAvailableDataUrl(url);
403 if (ir != null) {
404 cache.put(url, ir);
405 }
406 return ir;
407 }
408
409 ImageType type = name.toLowerCase().endsWith(".svg") ? ImageType.SVG : ImageType.OTHER;
410
411 if (name.startsWith("http://")) {
412 String url = name;
413 ImageResource ir = cache.get(url);
414 if (ir != null) return ir;
415 ir = getIfAvailableHttp(url, type);
416 if (ir != null) {
417 cache.put(url, ir);
418 }
419 return ir;
420 } else if (name.startsWith("wiki://")) {
421 ImageResource ir = cache.get(name);
422 if (ir != null) return ir;
423 ir = getIfAvailableWiki(name, type);
424 if (ir != null) {
425 cache.put(name, ir);
426 }
427 return ir;
428 }
429
430 if (subdir == null) {
431 subdir = "";
432 } else if (!subdir.isEmpty()) {
433 subdir += "/";
434 }
435 String[] extensions;
436 if (name.indexOf('.') != -1) {
437 extensions = new String[] { "" };
438 } else {
439 extensions = new String[] { ".png", ".svg"};
440 }
441 final int ARCHIVE = 0, LOCAL = 1;
442 for (int place : new Integer[] { ARCHIVE, LOCAL }) {
443 for (String ext : extensions) {
444
445 if (".svg".equals(ext)) {
446 type = ImageType.SVG;
447 } else if (".png".equals(ext)) {
448 type = ImageType.OTHER;
449 }
450
451 String full_name = subdir + name + ext;
452 String cache_name = full_name;
453 /* cache separately */
454 if (dirs != null && !dirs.isEmpty()) {
455 cache_name = "id:" + id + ":" + full_name;
456 if(archive != null) {
457 cache_name += ":" + archive.getName();
458 }
459 }
460
461 ImageResource ir = cache.get(cache_name);
462 if (ir != null) return ir;
463
464 switch (place) {
465 case ARCHIVE:
466 if (archive != null) {
467 ir = getIfAvailableZip(full_name, archive, inArchiveDir, type);
468 if (ir != null) {
469 cache.put(cache_name, ir);
470 return ir;
471 }
472 }
473 break;
474 case LOCAL:
475 // getImageUrl() does a ton of "stat()" calls and gets expensive
476 // and redundant when you have a whole ton of objects. So,
477 // index the cache by the name of the icon we're looking for
478 // and don't bother to create a URL unless we're actually
479 // creating the image.
480 URL path = getImageUrl(full_name, dirs, additionalClassLoaders);
481 if (path == null) {
482 continue;
483 }
484 ir = getIfAvailableLocalURL(path, type);
485 if (ir != null) {
486 cache.put(cache_name, ir);
487 return ir;
488 }
489 break;
490 }
491 }
492 }
493 return null;
494 }
495 }
496
497 private static ImageResource getIfAvailableHttp(String url, ImageType type) {
498 MirroredInputStream is = null;
499 try {
500 is = new MirroredInputStream(url,
501 new File(Main.pref.getCacheDirectory(), "images").getPath());
502 switch (type) {
503 case SVG:
504 URI uri = getSvgUniverse().loadSVG(is, Utils.fileToURL(is.getFile()).toString());
505 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
506 return svg == null ? null : new ImageResource(svg);
507 case OTHER:
508 BufferedImage img = null;
509 try {
510 img = ImageIO.read(Utils.fileToURL(is.getFile()));
511 } catch (IOException e) {
512 Main.warn("IOException while reading HTTP image: "+e.getMessage());
513 }
514 return img == null ? null : new ImageResource(img);
515 default:
516 throw new AssertionError();
517 }
518 } catch (IOException e) {
519 return null;
520 } finally {
521 Utils.close(is);
522 }
523 }
524
525 private static ImageResource getIfAvailableDataUrl(String url) {
526 try {
527 Matcher m = dataUrlPattern.matcher(url);
528 if (m.matches()) {
529 String mediatype = m.group(1);
530 String base64 = m.group(2);
531 String data = m.group(3);
532 byte[] bytes = ";base64".equals(base64)
533 ? Base64.decodeBase64(data)
534 : URLDecoder.decode(data, "utf-8").getBytes();
535 if (mediatype != null && mediatype.contains("image/svg+xml")) {
536 URI uri = getSvgUniverse().loadSVG(new StringReader(new String(bytes)), url);
537 return new ImageResource(getSvgUniverse().getDiagram(uri));
538 } else {
539 try {
540 return new ImageResource(ImageIO.read(new ByteArrayInputStream(bytes)));
541 } catch (IOException e) {
542 Main.warn("IOException while reading image: "+e.getMessage());
543 }
544 }
545 }
546 return null;
547 } catch (UnsupportedEncodingException ex) {
548 throw new RuntimeException(ex.getMessage(), ex);
549 }
550 }
551
552 private static ImageResource getIfAvailableWiki(String name, ImageType type) {
553 final Collection<String> defaultBaseUrls = Arrays.asList(
554 "http://wiki.openstreetmap.org/w/images/",
555 "http://upload.wikimedia.org/wikipedia/commons/",
556 "http://wiki.openstreetmap.org/wiki/File:"
557 );
558 final Collection<String> baseUrls = Main.pref.getCollection("image-provider.wiki.urls", defaultBaseUrls);
559
560 final String fn = name.substring(name.lastIndexOf('/') + 1);
561
562 ImageResource result = null;
563 for (String b : baseUrls) {
564 String url;
565 if (b.endsWith(":")) {
566 url = getImgUrlFromWikiInfoPage(b, fn);
567 if (url == null) {
568 continue;
569 }
570 } else {
571 final String fn_md5 = Utils.md5Hex(fn);
572 url = b + fn_md5.substring(0,1) + "/" + fn_md5.substring(0,2) + "/" + fn;
573 }
574 result = getIfAvailableHttp(url, type);
575 if (result != null) {
576 break;
577 }
578 }
579 return result;
580 }
581
582 private static ImageResource getIfAvailableZip(String full_name, File archive, String inArchiveDir, ImageType type) {
583 ZipFile zipFile = null;
584 try
585 {
586 zipFile = new ZipFile(archive);
587 if (inArchiveDir == null || inArchiveDir.equals(".")) {
588 inArchiveDir = "";
589 } else if (!inArchiveDir.isEmpty()) {
590 inArchiveDir += "/";
591 }
592 String entry_name = inArchiveDir + full_name;
593 ZipEntry entry = zipFile.getEntry(entry_name);
594 if(entry != null)
595 {
596 int size = (int)entry.getSize();
597 int offs = 0;
598 byte[] buf = new byte[size];
599 InputStream is = null;
600 try {
601 is = zipFile.getInputStream(entry);
602 switch (type) {
603 case SVG:
604 URI uri = getSvgUniverse().loadSVG(is, entry_name);
605 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
606 return svg == null ? null : new ImageResource(svg);
607 case OTHER:
608 while(size > 0)
609 {
610 int l = is.read(buf, offs, size);
611 offs += l;
612 size -= l;
613 }
614 BufferedImage img = null;
615 try {
616 img = ImageIO.read(new ByteArrayInputStream(buf));
617 } catch (IOException e) {
618 Main.warn(e);
619 }
620 return img == null ? null : new ImageResource(img);
621 default:
622 throw new AssertionError();
623 }
624 } finally {
625 Utils.close(is);
626 }
627 }
628 } catch (Exception e) {
629 Main.warn(tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
630 } finally {
631 Utils.close(zipFile);
632 }
633 return null;
634 }
635
636 private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
637 switch (type) {
638 case SVG:
639 URI uri = getSvgUniverse().loadSVG(path);
640 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
641 return svg == null ? null : new ImageResource(svg);
642 case OTHER:
643 BufferedImage img = null;
644 try {
645 img = ImageIO.read(path);
646 } catch (IOException e) {
647 Main.warn(e);
648 }
649 return img == null ? null : new ImageResource(img);
650 default:
651 throw new AssertionError();
652 }
653 }
654
655 private static URL getImageUrl(String path, String name, Collection<ClassLoader> additionalClassLoaders) {
656 if (path != null && path.startsWith("resource://")) {
657 String p = path.substring("resource://".length());
658 Collection<ClassLoader> classLoaders = new ArrayList<ClassLoader>(PluginHandler.getResourceClassLoaders());
659 if (additionalClassLoaders != null) {
660 classLoaders.addAll(additionalClassLoaders);
661 }
662 for (ClassLoader source : classLoaders) {
663 URL res;
664 if ((res = source.getResource(p + name)) != null)
665 return res;
666 }
667 } else {
668 File f = new File(path, name);
669 if ((path != null || f.isAbsolute()) && f.exists())
670 return Utils.fileToURL(f);
671 }
672 return null;
673 }
674
675 private static URL getImageUrl(String imageName, Collection<String> dirs, Collection<ClassLoader> additionalClassLoaders) {
676 URL u = null;
677
678 // Try passed directories first
679 if (dirs != null) {
680 for (String name : dirs) {
681 try {
682 u = getImageUrl(name, imageName, additionalClassLoaders);
683 if (u != null)
684 return u;
685 } catch (SecurityException e) {
686 Main.warn(tr(
687 "Failed to access directory ''{0}'' for security reasons. Exception was: {1}",
688 name, e.toString()));
689 }
690
691 }
692 }
693 // Try user-preference directory
694 String dir = Main.pref.getPreferencesDir() + "images";
695 try {
696 u = getImageUrl(dir, imageName, additionalClassLoaders);
697 if (u != null)
698 return u;
699 } catch (SecurityException e) {
700 Main.warn(tr(
701 "Failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
702 .toString()));
703 }
704
705 // Absolute path?
706 u = getImageUrl(null, imageName, additionalClassLoaders);
707 if (u != null)
708 return u;
709
710 // Try plugins and josm classloader
711 u = getImageUrl("resource://images/", imageName, additionalClassLoaders);
712 if (u != null)
713 return u;
714
715 // Try all other resource directories
716 for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
717 u = getImageUrl(location + "images", imageName, additionalClassLoaders);
718 if (u != null)
719 return u;
720 u = getImageUrl(location, imageName, additionalClassLoaders);
721 if (u != null)
722 return u;
723 }
724
725 return null;
726 }
727
728 /**
729 * Reads the wiki page on a certain file in html format in order to find the real image URL.
730 */
731 private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
732
733 /** Quit parsing, when a certain condition is met */
734 class SAXReturnException extends SAXException {
735 private String result;
736
737 public SAXReturnException(String result) {
738 this.result = result;
739 }
740
741 public String getResult() {
742 return result;
743 }
744 }
745
746 try {
747 final XMLReader parser = XMLReaderFactory.createXMLReader();
748 parser.setContentHandler(new DefaultHandler() {
749 @Override
750 public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
751 if (localName.equalsIgnoreCase("img")) {
752 String val = atts.getValue("src");
753 if (val.endsWith(fn))
754 throw new SAXReturnException(val); // parsing done, quit early
755 }
756 }
757 });
758
759 parser.setEntityResolver(new EntityResolver() {
760 @Override
761 public InputSource resolveEntity (String publicId, String systemId) {
762 return new InputSource(new ByteArrayInputStream(new byte[0]));
763 }
764 });
765
766 parser.parse(new InputSource(new MirroredInputStream(
767 base + fn,
768 new File(Main.pref.getPreferencesDir(), "images").toString()
769 )));
770 } catch (SAXReturnException r) {
771 return r.getResult();
772 } catch (Exception e) {
773 Main.warn("Parsing " + base + fn + " failed:\n" + e);
774 return null;
775 }
776 Main.warn("Parsing " + base + fn + " failed: Unexpected content.");
777 return null;
778 }
779
780 public static Cursor getCursor(String name, String overlay) {
781 ImageIcon img = get("cursor", name);
782 if (overlay != null) {
783 img = overlay(img, ImageProvider.get("cursor/modifier/" + overlay), OverlayPosition.SOUTHEAST);
784 }
785 Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
786 name.equals("crosshair") ? new Point(10, 10) : new Point(3, 2), "Cursor");
787 return c;
788 }
789
790 /**
791 * Decorate one icon with an overlay icon.
792 *
793 * @param ground the base image
794 * @param overlay the overlay image (can be smaller than the base image)
795 * @param pos position of the overlay image inside the base image (positioned
796 * in one of the corners)
797 * @return an icon that represent the overlay of the two given icons. The second icon is layed
798 * on the first relative to the given position.
799 */
800 public static ImageIcon overlay(Icon ground, Icon overlay, OverlayPosition pos) {
801 GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
802 .getDefaultConfiguration();
803 int w = ground.getIconWidth();
804 int h = ground.getIconHeight();
805 int wo = overlay.getIconWidth();
806 int ho = overlay.getIconHeight();
807 BufferedImage img = conf.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
808 Graphics g = img.createGraphics();
809 ground.paintIcon(null, g, 0, 0);
810 int x = 0, y = 0;
811 switch (pos) {
812 case NORTHWEST:
813 x = 0;
814 y = 0;
815 break;
816 case NORTHEAST:
817 x = w - wo;
818 y = 0;
819 break;
820 case SOUTHWEST:
821 x = 0;
822 y = h - ho;
823 break;
824 case SOUTHEAST:
825 x = w - wo;
826 y = h - ho;
827 break;
828 }
829 overlay.paintIcon(null, g, x, y);
830 return new ImageIcon(img);
831 }
832
833 /** 90 degrees in radians units */
834 final static double DEGREE_90 = 90.0 * Math.PI / 180.0;
835
836 /**
837 * Creates a rotated version of the input image.
838 *
839 * @param img the image to be rotated.
840 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
841 * will mod it with 360 before using it. More over for caching performance, it will be rounded to
842 * an entire value between 0 and 360.
843 *
844 * @return the image after rotating.
845 * @since 6172
846 */
847 public static Image createRotatedImage(Image img, double rotatedAngle) {
848 return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
849 }
850
851 /**
852 * Creates a rotated version of the input image, scaled to the given dimension.
853 *
854 * @param img the image to be rotated.
855 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
856 * will mod it with 360 before using it. More over for caching performance, it will be rounded to
857 * an entire value between 0 and 360.
858 * @param dimension The requested dimensions. Use (-1,-1) for the original size
859 * and (width, -1) to set the width, but otherwise scale the image proportionally.
860 * @return the image after rotating and scaling.
861 * @since 6172
862 */
863 public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
864 CheckParameterUtil.ensureParameterNotNull(img, "img");
865
866 // convert rotatedAngle to an integer value from 0 to 360
867 Long originalAngle = Math.round(rotatedAngle % 360);
868 if (rotatedAngle != 0 && originalAngle == 0) {
869 originalAngle = 360L;
870 }
871
872 ImageResource imageResource = null;
873
874 synchronized (ROTATE_CACHE) {
875 Map<Long, ImageResource> cacheByAngle = ROTATE_CACHE.get(img);
876 if (cacheByAngle == null) {
877 ROTATE_CACHE.put(img, cacheByAngle = new HashMap<Long, ImageResource>());
878 }
879
880 imageResource = cacheByAngle.get(originalAngle);
881
882 if (imageResource == null) {
883 // convert originalAngle to a value from 0 to 90
884 double angle = originalAngle % 90;
885 if (originalAngle != 0.0 && angle == 0.0) {
886 angle = 90.0;
887 }
888
889 double radian = Math.toRadians(angle);
890
891 new ImageIcon(img); // load completely
892 int iw = img.getWidth(null);
893 int ih = img.getHeight(null);
894 int w;
895 int h;
896
897 if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
898 w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
899 h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
900 } else {
901 w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
902 h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
903 }
904 Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
905 cacheByAngle.put(originalAngle, imageResource = new ImageResource(image));
906 Graphics g = image.getGraphics();
907 Graphics2D g2d = (Graphics2D) g.create();
908
909 // calculate the center of the icon.
910 int cx = iw / 2;
911 int cy = ih / 2;
912
913 // move the graphics center point to the center of the icon.
914 g2d.translate(w / 2, h / 2);
915
916 // rotate the graphics about the center point of the icon
917 g2d.rotate(Math.toRadians(originalAngle));
918
919 g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
920 g2d.drawImage(img, -cx, -cy, null);
921
922 g2d.dispose();
923 new ImageIcon(image); // load completely
924 }
925 return imageResource.getImageIcon(dimension).getImage();
926 }
927 }
928
929 /**
930 * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
931 *
932 * @param img the image to be scaled down.
933 * @param maxSize the maximum size in pixels (both for width and height)
934 *
935 * @return the image after scaling.
936 * @since 6172
937 */
938 public static Image createBoundedImage(Image img, int maxSize) {
939 return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
940 }
941
942 /**
943 * Replies the icon for an OSM primitive type
944 * @param type the type
945 * @return the icon
946 */
947 public static ImageIcon get(OsmPrimitiveType type) {
948 CheckParameterUtil.ensureParameterNotNull(type, "type");
949 return get("data", type.getAPIName());
950 }
951
952 public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
953 float realWidth = svg.getWidth();
954 float realHeight = svg.getHeight();
955 int width = Math.round(realWidth);
956 int height = Math.round(realHeight);
957 Double scaleX = null, scaleY = null;
958 if (dim.width != -1) {
959 width = dim.width;
960 scaleX = (double) width / realWidth;
961 if (dim.height == -1) {
962 scaleY = scaleX;
963 height = (int) Math.round(realHeight * scaleY);
964 } else {
965 height = dim.height;
966 scaleY = (double) height / realHeight;
967 }
968 } else if (dim.height != -1) {
969 height = dim.height;
970 scaleX = scaleY = (double) height / realHeight;
971 width = (int) Math.round(realWidth * scaleX);
972 }
973 if (width == 0 || height == 0) {
974 return null;
975 }
976 BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
977 Graphics2D g = img.createGraphics();
978 g.setClip(0, 0, width, height);
979 if (scaleX != null && scaleY != null) {
980 g.scale(scaleX, scaleY);
981 }
982 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
983 try {
984 svg.render(g);
985 } catch (SVGException ex) {
986 return null;
987 }
988 return img;
989 }
990
991 private static SVGUniverse getSvgUniverse() {
992 if (svgUniverse == null) {
993 svgUniverse = new SVGUniverse();
994 }
995 return svgUniverse;
996 }
997}
Note: See TracBrowser for help on using the repository browser.