import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JFrame; public class ImageDimensions extends JFrame { protected static Toolkit tool = Toolkit.getDefaultToolkit(); public ImageDimensions() { } protected void calculateHeightWidth() throws InterruptedException { Image image = null; try { image = tool.createImage(new URL("Image URL")); } catch (MalformedURLException e) { e.printStackTrace(); }catch(Exception e1){ e1.printStackTrace(); } MediaTracker mTracker = new MediaTracker(this); mTracker.addImage(image, 1); int i = 0; do { mTracker.waitForID(1); //added counter and break for the 404 or bad url i++; if (i==5) break; } while (mTracker.statusID(1, true) != MediaTracker.COMPLETE); System.out.println(image.getHeight(null)); System.out.println(image.getWidth(null)); } public static void main(String[] args) { try { new ImageDimensions().calculateHeightWidth(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Misc Java related problems I faced and solutions I found. Hope this helps other developers.
Sunday, October 25, 2009
Java Swing Example: Image dimension from url
This code can be used to get the dimension of any image using its url. Minor tweaks can be made to get localized image dimensions too.Hope this helps.
Subscribe to:
Post Comments (Atom)
1 comment:
Helpfull piece of code
Post a Comment