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。
有什么想法吗?
答案 0 :(得分: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( "http://www.ecs.soton.ac.uk/~dpd98r/gfx/Mavis2.jpg");
/* Create a new MediaTracker linked to this Component */
MedaiTracker m = new MedaiTracker( 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() & MedaiTracker.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!");
}
}
答案 1 :(得分: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对象"