Aditya Kumar
Aditya Kumar

Reputation: 297

Image made through Toolkit returns -1 as width,height

java.awt.Toolkit kit = Toolkit.getDefaultToolkit();
try {
   java.awt.Image img,ig;
   img = kit.getImage("/home/aditya/Pictures/tile.png");
   ig =
      javax.imageio.ImageIO.read(
         new java.io.File("/home/aditya/Pictures/tile.png"));
}
int w  = img.getWidth(null);
int wp = ig .getWidth(null);
int h  = img.getHeight(null);
int hp = ig .getHeight(null);
System.out.println(wp+" "+hp+" "+w+" "+h); 

Always gives this output

59 64 -1 -1

i.e. width,height of image created through toolkit always returns -1.

Any idea ?

Upvotes: 2

Views: 509

Answers (2)

matt
matt

Reputation: 12346

Instead of using null for getWidth, you can use an ImageObserver.

ImageObserver a = new ImageObserver(){
                      imageUpdate​(Image img, int infoflags, int x, int y, int width, int height){
        System.out.println("After loading: " + x + ", " + y + ", " +width + ", " + height);
    }
}

Then when you get the width, you'll get -1 the first call, but the observer will be notified when it is changed. "if the width is not yet known, this method returns -1 and the specified ImageObserver object is notified later"

Upvotes: 1

Aubin
Aubin

Reputation: 14853

Loading of images using awt is asynchronous.

Look at this tutorial.

class test extends Component
{
    test()
    {
        /* Get the toolkit from this Component */
        Toolkit t = getToolkit();
        /* Begin a retrieval of a remote image */
        Image   i = t.getImage( "https://cdn.southampton.ac.uk/assets/imported/transforms/site/depth/Action_BackgroundImage/E8813999F2F94220B91699A33F794636/201117_syndicut_southamptonUni_Homepage_banner.png_SIA_JPG_fit_to_width_FULL.jpg");
        /* Create a new MediaTracker linked to this Component */
        MediaTracker m = new MediaTracker( this );
        /* Add the loading image to the MediaTracker,
           with an ID of 1 */
        m.addImage( i, 1 );
        /* Explicitly wait for the image to load */
        try
        {
            m.waitForAll();
        }
        /* Catch the exception */
        catch( InterruptedException e )
        {
            System.out.println("Loading of the image was interrupted" );
        }

        /* Check the status */
        if( m.status() & MediaTracker.LOADING )
            System.out.println("Still Loading - oops, we should never be here!");
        if( m.status() & MediaTracker.ABORTED )
            System.out.println("Loading of image aborted");
        if( m.status() & MediaTracker.ERRORED )
            System.out.println("Image was errored");
        if( m.status() & MediaTracker.COMPLETE )
            System.out.println("Image load complete!");
    }
}

Upvotes: 1

Related Questions