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

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

Sonar - fix recently introduced issues

  • Property svn:eol-style set to native
File size: 34.9 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
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 System.err.println(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 try {
399 if (name.startsWith("data:")) {
400 Matcher m = dataUrlPattern.matcher(name);
401 if (m.matches()) {
402 String mediatype = m.group(1);
403 String base64 = m.group(2);
404 String data = m.group(3);
405 byte[] bytes = ";base64".equals(base64)
406 ? Base64.decodeBase64(data)
407 : URLDecoder.decode(data, "utf-8").getBytes();
408 if (mediatype != null && mediatype.contains("image/svg+xml")) {
409 URI uri = getSvgUniverse().loadSVG(new StringReader(new String(bytes)), name);
410 return new ImageResource(getSvgUniverse().getDiagram(uri));
411 } else {
412 try {
413 return new ImageResource(ImageIO.read(new ByteArrayInputStream(bytes)));
414 } catch (IOException e) {}
415 }
416 }
417 }
418 } catch (UnsupportedEncodingException ex) {
419 throw new RuntimeException(ex.getMessage(), ex);
420 }
421
422 ImageType type = name.toLowerCase().endsWith(".svg") ? ImageType.SVG : ImageType.OTHER;
423
424 if (name.startsWith("http://")) {
425 String url = name;
426 ImageResource ir = cache.get(url);
427 if (ir != null) return ir;
428 ir = getIfAvailableHttp(url, type);
429 if (ir != null) {
430 cache.put(url, ir);
431 }
432 return ir;
433 } else if (name.startsWith("wiki://")) {
434 ImageResource ir = cache.get(name);
435 if (ir != null) return ir;
436 ir = getIfAvailableWiki(name, type);
437 if (ir != null) {
438 cache.put(name, ir);
439 }
440 return ir;
441 }
442
443 if (subdir == null) {
444 subdir = "";
445 } else if (!subdir.isEmpty()) {
446 subdir += "/";
447 }
448 String[] extensions;
449 if (name.indexOf('.') != -1) {
450 extensions = new String[] { "" };
451 } else {
452 extensions = new String[] { ".png", ".svg"};
453 }
454 final int ARCHIVE = 0, LOCAL = 1;
455 for (int place : new Integer[] { ARCHIVE, LOCAL }) {
456 for (String ext : extensions) {
457
458 if (".svg".equals(ext)) {
459 type = ImageType.SVG;
460 } else if (".png".equals(ext)) {
461 type = ImageType.OTHER;
462 }
463
464 String full_name = subdir + name + ext;
465 String cache_name = full_name;
466 /* cache separately */
467 if (dirs != null && !dirs.isEmpty()) {
468 cache_name = "id:" + id + ":" + full_name;
469 if(archive != null) {
470 cache_name += ":" + archive.getName();
471 }
472 }
473
474 ImageResource ir = cache.get(cache_name);
475 if (ir != null) return ir;
476
477 switch (place) {
478 case ARCHIVE:
479 if (archive != null) {
480 ir = getIfAvailableZip(full_name, archive, inArchiveDir, type);
481 if (ir != null) {
482 cache.put(cache_name, ir);
483 return ir;
484 }
485 }
486 break;
487 case LOCAL:
488 // getImageUrl() does a ton of "stat()" calls and gets expensive
489 // and redundant when you have a whole ton of objects. So,
490 // index the cache by the name of the icon we're looking for
491 // and don't bother to create a URL unless we're actually
492 // creating the image.
493 URL path = getImageUrl(full_name, dirs, additionalClassLoaders);
494 if (path == null) {
495 continue;
496 }
497 ir = getIfAvailableLocalURL(path, type);
498 if (ir != null) {
499 cache.put(cache_name, ir);
500 return ir;
501 }
502 break;
503 }
504 }
505 }
506 return null;
507 }
508 }
509
510 private static ImageResource getIfAvailableHttp(String url, ImageType type) {
511 MirroredInputStream is = null;
512 try {
513 is = new MirroredInputStream(url,
514 new File(Main.pref.getCacheDirectory(), "images").getPath());
515 switch (type) {
516 case SVG:
517 URI uri = getSvgUniverse().loadSVG(is, is.getFile().toURI().toURL().toString());
518 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
519 return svg == null ? null : new ImageResource(svg);
520 case OTHER:
521 BufferedImage img = null;
522 try {
523 img = ImageIO.read(is.getFile().toURI().toURL());
524 } catch (IOException e) {}
525 return img == null ? null : new ImageResource(img);
526 default:
527 throw new AssertionError();
528 }
529 } catch (IOException e) {
530 return null;
531 } finally {
532 Utils.close(is);
533 }
534 }
535
536 private static ImageResource getIfAvailableWiki(String name, ImageType type) {
537 final Collection<String> defaultBaseUrls = Arrays.asList(
538 "http://wiki.openstreetmap.org/w/images/",
539 "http://upload.wikimedia.org/wikipedia/commons/",
540 "http://wiki.openstreetmap.org/wiki/File:"
541 );
542 final Collection<String> baseUrls = Main.pref.getCollection("image-provider.wiki.urls", defaultBaseUrls);
543
544 final String fn = name.substring(name.lastIndexOf('/') + 1);
545
546 ImageResource result = null;
547 for (String b : baseUrls) {
548 String url;
549 if (b.endsWith(":")) {
550 url = getImgUrlFromWikiInfoPage(b, fn);
551 if (url == null) {
552 continue;
553 }
554 } else {
555 final String fn_md5 = Utils.md5Hex(fn);
556 url = b + fn_md5.substring(0,1) + "/" + fn_md5.substring(0,2) + "/" + fn;
557 }
558 result = getIfAvailableHttp(url, type);
559 if (result != null) {
560 break;
561 }
562 }
563 return result;
564 }
565
566 private static ImageResource getIfAvailableZip(String full_name, File archive, String inArchiveDir, ImageType type) {
567 ZipFile zipFile = null;
568 try
569 {
570 zipFile = new ZipFile(archive);
571 if (inArchiveDir == null || inArchiveDir.equals(".")) {
572 inArchiveDir = "";
573 } else if (!inArchiveDir.isEmpty()) {
574 inArchiveDir += "/";
575 }
576 String entry_name = inArchiveDir + full_name;
577 ZipEntry entry = zipFile.getEntry(entry_name);
578 if(entry != null)
579 {
580 int size = (int)entry.getSize();
581 int offs = 0;
582 byte[] buf = new byte[size];
583 InputStream is = null;
584 try {
585 is = zipFile.getInputStream(entry);
586 switch (type) {
587 case SVG:
588 URI uri = getSvgUniverse().loadSVG(is, entry_name);
589 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
590 return svg == null ? null : new ImageResource(svg);
591 case OTHER:
592 while(size > 0)
593 {
594 int l = is.read(buf, offs, size);
595 offs += l;
596 size -= l;
597 }
598 BufferedImage img = null;
599 try {
600 img = ImageIO.read(new ByteArrayInputStream(buf));
601 } catch (IOException e) {}
602 return img == null ? null : new ImageResource(img);
603 default:
604 throw new AssertionError();
605 }
606 } finally {
607 Utils.close(is);
608 }
609 }
610 } catch (Exception e) {
611 System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
612 } finally {
613 Utils.close(zipFile);
614 }
615 return null;
616 }
617
618 private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
619 switch (type) {
620 case SVG:
621 URI uri = getSvgUniverse().loadSVG(path);
622 SVGDiagram svg = getSvgUniverse().getDiagram(uri);
623 return svg == null ? null : new ImageResource(svg);
624 case OTHER:
625 BufferedImage img = null;
626 try {
627 img = ImageIO.read(path);
628 } catch (IOException e) {}
629 return img == null ? null : new ImageResource(img);
630 default:
631 throw new AssertionError();
632 }
633 }
634
635 private static URL getImageUrl(String path, String name, Collection<ClassLoader> additionalClassLoaders) {
636 if (path != null && path.startsWith("resource://")) {
637 String p = path.substring("resource://".length());
638 Collection<ClassLoader> classLoaders = new ArrayList<ClassLoader>(PluginHandler.getResourceClassLoaders());
639 if (additionalClassLoaders != null) {
640 classLoaders.addAll(additionalClassLoaders);
641 }
642 for (ClassLoader source : classLoaders) {
643 URL res;
644 if ((res = source.getResource(p + name)) != null)
645 return res;
646 }
647 } else {
648 try {
649 File f = new File(path, name);
650 if ((path != null || f.isAbsolute()) && f.exists())
651 return f.toURI().toURL();
652 } catch (MalformedURLException e) {
653 }
654 }
655 return null;
656 }
657
658 private static URL getImageUrl(String imageName, Collection<String> dirs, Collection<ClassLoader> additionalClassLoaders) {
659 URL u = null;
660
661 // Try passed directories first
662 if (dirs != null) {
663 for (String name : dirs) {
664 try {
665 u = getImageUrl(name, imageName, additionalClassLoaders);
666 if (u != null)
667 return u;
668 } catch (SecurityException e) {
669 System.out.println(tr(
670 "Warning: failed to access directory ''{0}'' for security reasons. Exception was: {1}",
671 name, e.toString()));
672 }
673
674 }
675 }
676 // Try user-preference directory
677 String dir = Main.pref.getPreferencesDir() + "images";
678 try {
679 u = getImageUrl(dir, imageName, additionalClassLoaders);
680 if (u != null)
681 return u;
682 } catch (SecurityException e) {
683 System.out.println(tr(
684 "Warning: failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
685 .toString()));
686 }
687
688 // Absolute path?
689 u = getImageUrl(null, imageName, additionalClassLoaders);
690 if (u != null)
691 return u;
692
693 // Try plugins and josm classloader
694 u = getImageUrl("resource://images/", imageName, additionalClassLoaders);
695 if (u != null)
696 return u;
697
698 // Try all other resource directories
699 for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
700 u = getImageUrl(location + "images", imageName, additionalClassLoaders);
701 if (u != null)
702 return u;
703 u = getImageUrl(location, imageName, additionalClassLoaders);
704 if (u != null)
705 return u;
706 }
707
708 return null;
709 }
710
711 /**
712 * Reads the wiki page on a certain file in html format in order to find the real image URL.
713 */
714 private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
715
716 /** Quit parsing, when a certain condition is met */
717 class SAXReturnException extends SAXException {
718 private String result;
719
720 public SAXReturnException(String result) {
721 this.result = result;
722 }
723
724 public String getResult() {
725 return result;
726 }
727 }
728
729 try {
730 final XMLReader parser = XMLReaderFactory.createXMLReader();
731 parser.setContentHandler(new DefaultHandler() {
732 @Override
733 public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
734 System.out.println();
735 if (localName.equalsIgnoreCase("img")) {
736 String val = atts.getValue("src");
737 if (val.endsWith(fn))
738 throw new SAXReturnException(val); // parsing done, quit early
739 }
740 }
741 });
742
743 parser.setEntityResolver(new EntityResolver() {
744 @Override
745 public InputSource resolveEntity (String publicId, String systemId) {
746 return new InputSource(new ByteArrayInputStream(new byte[0]));
747 }
748 });
749
750 parser.parse(new InputSource(new MirroredInputStream(
751 base + fn,
752 new File(Main.pref.getPreferencesDir(), "images").toString()
753 )));
754 } catch (SAXReturnException r) {
755 return r.getResult();
756 } catch (Exception e) {
757 System.out.println("INFO: parsing " + base + fn + " failed:\n" + e);
758 return null;
759 }
760 System.out.println("INFO: parsing " + base + fn + " failed: Unexpected content.");
761 return null;
762 }
763
764 public static Cursor getCursor(String name, String overlay) {
765 ImageIcon img = get("cursor", name);
766 if (overlay != null) {
767 img = overlay(img, ImageProvider.get("cursor/modifier/" + overlay), OverlayPosition.SOUTHEAST);
768 }
769 Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
770 name.equals("crosshair") ? new Point(10, 10) : new Point(3, 2), "Cursor");
771 return c;
772 }
773
774 /**
775 * Decorate one icon with an overlay icon.
776 *
777 * @param ground the base image
778 * @param overlay the overlay image (can be smaller than the base image)
779 * @param pos position of the overlay image inside the base image (positioned
780 * in one of the corners)
781 * @return an icon that represent the overlay of the two given icons. The second icon is layed
782 * on the first relative to the given position.
783 */
784 public static ImageIcon overlay(Icon ground, Icon overlay, OverlayPosition pos) {
785 GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
786 .getDefaultConfiguration();
787 int w = ground.getIconWidth();
788 int h = ground.getIconHeight();
789 int wo = overlay.getIconWidth();
790 int ho = overlay.getIconHeight();
791 BufferedImage img = conf.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
792 Graphics g = img.createGraphics();
793 ground.paintIcon(null, g, 0, 0);
794 int x = 0, y = 0;
795 switch (pos) {
796 case NORTHWEST:
797 x = 0;
798 y = 0;
799 break;
800 case NORTHEAST:
801 x = w - wo;
802 y = 0;
803 break;
804 case SOUTHWEST:
805 x = 0;
806 y = h - ho;
807 break;
808 case SOUTHEAST:
809 x = w - wo;
810 y = h - ho;
811 break;
812 }
813 overlay.paintIcon(null, g, x, y);
814 return new ImageIcon(img);
815 }
816
817 /** 90 degrees in radians units */
818 final static double DEGREE_90 = 90.0 * Math.PI / 180.0;
819
820 /**
821 * Creates a rotated version of the input image.
822 *
823 * @param img the image to be rotated.
824 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
825 * will mod it with 360 before using it. More over for caching performance, it will be rounded to
826 * an entire value between 0 and 360.
827 *
828 * @return the image after rotating.
829 * @since 6172
830 */
831 public static Image createRotatedImage(Image img, double rotatedAngle) {
832 return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
833 }
834
835 /**
836 * Creates a rotated version of the input image, scaled to the given dimension.
837 *
838 * @param img the image to be rotated.
839 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
840 * will mod it with 360 before using it. More over for caching performance, it will be rounded to
841 * an entire value between 0 and 360.
842 * @param dimension The requested dimensions. Use (-1,-1) for the original size
843 * and (width, -1) to set the width, but otherwise scale the image proportionally.
844 * @return the image after rotating and scaling.
845 * @since 6172
846 */
847 public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
848 CheckParameterUtil.ensureParameterNotNull(img, "img");
849
850 // convert rotatedAngle to an integer value from 0 to 360
851 Long originalAngle = Math.round(rotatedAngle % 360);
852 if (rotatedAngle != 0 && originalAngle == 0) {
853 originalAngle = 360L;
854 }
855
856 ImageResource imageResource = null;
857
858 synchronized (ROTATE_CACHE) {
859 Map<Long, ImageResource> cacheByAngle = ROTATE_CACHE.get(img);
860 if (cacheByAngle == null) {
861 ROTATE_CACHE.put(img, cacheByAngle = new HashMap<Long, ImageResource>());
862 }
863
864 imageResource = cacheByAngle.get(originalAngle);
865
866 if (imageResource == null) {
867 // convert originalAngle to a value from 0 to 90
868 double angle = originalAngle % 90;
869 if (originalAngle != 0.0 && angle == 0.0) {
870 angle = 90.0;
871 }
872
873 double radian = Math.toRadians(angle);
874
875 new ImageIcon(img); // load completely
876 int iw = img.getWidth(null);
877 int ih = img.getHeight(null);
878 int w;
879 int h;
880
881 if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
882 w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
883 h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
884 } else {
885 w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
886 h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
887 }
888 Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
889 cacheByAngle.put(originalAngle, imageResource = new ImageResource(image));
890 Graphics g = image.getGraphics();
891 Graphics2D g2d = (Graphics2D) g.create();
892
893 // calculate the center of the icon.
894 int cx = iw / 2;
895 int cy = ih / 2;
896
897 // move the graphics center point to the center of the icon.
898 g2d.translate(w / 2, h / 2);
899
900 // rotate the graphics about the center point of the icon
901 g2d.rotate(Math.toRadians(originalAngle));
902
903 g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
904 g2d.drawImage(img, -cx, -cy, null);
905
906 g2d.dispose();
907 new ImageIcon(image); // load completely
908 }
909 return imageResource.getImageIcon(dimension).getImage();
910 }
911 }
912
913 /**
914 * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
915 *
916 * @param img the image to be scaled down.
917 * @param maxSize the maximum size in pixels (both for width and height)
918 *
919 * @return the image after scaling.
920 * @since 6172
921 */
922 public static Image createBoundedImage(Image img, int maxSize) {
923 return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
924 }
925
926 /**
927 * Replies the icon for an OSM primitive type
928 * @param type the type
929 * @return the icon
930 */
931 public static ImageIcon get(OsmPrimitiveType type) {
932 CheckParameterUtil.ensureParameterNotNull(type, "type");
933 return get("data", type.getAPIName());
934 }
935
936 public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
937 float realWidth = svg.getWidth();
938 float realHeight = svg.getHeight();
939 int width = Math.round(realWidth);
940 int height = Math.round(realHeight);
941 Double scaleX = null, scaleY = null;
942 if (dim.width != -1) {
943 width = dim.width;
944 scaleX = (double) width / realWidth;
945 if (dim.height == -1) {
946 scaleY = scaleX;
947 height = (int) Math.round(realHeight * scaleY);
948 } else {
949 height = dim.height;
950 scaleY = (double) height / realHeight;
951 }
952 } else if (dim.height != -1) {
953 height = dim.height;
954 scaleX = scaleY = (double) height / realHeight;
955 width = (int) Math.round(realWidth * scaleX);
956 }
957 if (width == 0 || height == 0) {
958 return null;
959 }
960 BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
961 Graphics2D g = img.createGraphics();
962 g.setClip(0, 0, width, height);
963 if (scaleX != null && scaleY != null) {
964 g.scale(scaleX, scaleY);
965 }
966 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
967 try {
968 svg.render(g);
969 } catch (SVGException ex) {
970 return null;
971 }
972 return img;
973 }
974
975 private static SVGUniverse getSvgUniverse() {
976 if (svgUniverse == null) {
977 svgUniverse = new SVGUniverse();
978 }
979 return svgUniverse;
980 }
981}
Note: See TracBrowser for help on using the repository browser.