/** * Return whether the given icon is animated. Currently assumes the original filename ends with * "animated.gif". */ public static boolean isAnimated(Icon icon) { // Kind of a hack... can we see if it's an animated GIF by looking // inside the ImageIcon some other way? if (icon instanceof ImageIcon) { // NOTE: icon.toString() may return null! String label = icon.toString(); if (label != null && label.indexOf("animated.gif") != -1) return true; } return false; }
/** Returns whether the given icon is an animated GIF. */ public static boolean isAnimated(Icon icon) { if (icon instanceof ImageIcon) { Image image = ((ImageIcon) icon).getImage(); if (image != null) { // Quick check for commonly-occurring animated GIF comment Object comment = image.getProperty("comment", null); if (String.valueOf(comment).startsWith("GifBuilder")) return true; // Check cache of already-decoded images if (decoded.containsKey(image)) { return Boolean.TRUE.equals(decoded.get(image)); } InputStream is = null; try { URL url = new URL(icon.toString()); is = url.openConnection().getInputStream(); } catch (Exception e) { e.printStackTrace(); } if (is == null) { try { // Beware: lots of hackery to obtain the image input stream // Be sure to catch security exceptions ImageProducer p = image.getSource(); // [macavity] - below rem'd lines don't compile on mac // if (p instanceof InputStreamImageSource) { // Method m = // InputStreamImageSource.class.getDeclaredMethod("getDecoder", null); // m.setAccessible(true); // ImageDecoder d = (ImageDecoder)m.invoke(p, null); // if (d instanceof GifImageDecoder) { // GifImageDecoder gd = (GifImageDecoder)d; // Field input = // ImageDecoder.class.getDeclaredField("input"); // input.setAccessible(true); // is = (InputStream)input.get(gd); // } // } } catch (Exception e) { e.printStackTrace(); } } if (is != null) { GifDecoder decoder = new GifDecoder(); decoder.read(is); boolean animated = decoder.getFrameCount() > 1; decoded.put(image, Boolean.valueOf(animated)); return animated; } } return false; } return icon instanceof AnimatedIcon; }