2
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); 

总是给出这个输出

59 64 -1 -1

即通过工具包创建的图像的宽度、高度总是返回-1。

任何想法 ?

4

2 回答 2

1

使用 awt 加载图像是异步的。

看看这个教程

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!");
    }
}
于 2013-02-27T20:56:08.227 回答
0

您可以使用 ImageObserver,而不是为 getWidth 使用 null。

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);
    }
}

然后当你得到宽度时,你会在第一次调用时得到-1,但是当它改变时会通知观察者。“如果宽度未知,则此方法返回-1,稍后通知指定的 ImageObserver 对象”

于 2021-08-09T12:39:04.927 回答