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。
有什么想法吗?
最佳答案
使用 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!");
}
}
关于java - 通过 Toolkit 制作的图像返回 -1 作为宽度、高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121863/