2013-07-11 43 views
2

我尝试了很多方法将Applet类中的图像转换为Applet程序中的BufferedImage。而且我有一种方法在从netbeans运行时工作正常。但通过浏览器运行时,相同的代码不起作用。我试图代码是将图像转换为小应用程序中的缓冲图像

ImageIcon icon = new ImageIcon(orgImage); 
BufferedImage buffer = ((ToolkitImage) icon.getImage()).getBufferedImage(); 

也试过以下

1) BufferedImage buffer = ((ToolkitImage) orgImage).getBufferedImage(); 

2) BufferedImage buffer = new BufferedImage(
    orgImage.getWidth(null), orgImage.getWidth(null), BufferedImage.TYPE_INT_RGB); 
    buffer.getGraphics().drawImage(orgImage, 0, 0, null); 

orgImage是彩色图像。

缓冲区是在所有这些情况下,空..

如何解决我的问题?

+0

1)为了更好地提供帮助,请发布[SSCCE](http://sscce.org/)。 2)'..drawImage(orgImage,0,0,null);'理想情况下''drawImage(orgImage,0,0,this);'3)“缓冲区在所有这些情况下都是空的。理解它在第二种情况下如何可能为空,但是SSCCE应该澄清...... –

回答

2

要将图像转换成一个缓冲的图像,你可以使用下面的功能:

/** 
* Converts a given Image into a BufferedImage 
* 
* @param img The Image to be converted 
* @return The converted BufferedImage 
*/ 
public BufferedImage toBufferedImage(Image img){ 
    if (img instanceof BufferedImage) { 
     return (BufferedImage) img; 
    } 
    // Create a buffered image with transparency 
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 
    // Draw the image on to the buffered image 
    Graphics2D bGr = bimage.createGraphics(); 
    bGr.drawImage(img, 0, 0, null); 
    bGr.dispose(); 
    // Return the buffered image 
    return bimage; 
} 

粘贴在你的类的任意位置,并使用下面的代码:

BufferedImage bi = toBufferedImage(orgImage); 

〜祺最大

+0

根据加载的方式,“Image”可能没有完全实现,这意味着如果没有某种'ImageObserver','drawImage '方法可能会导致没有绘制任何东西...... – MadProgrammer

+0

如果图像未加载,它将为空na? –

+0

我在一个线程中编写了代码..代码写在一个if条件中,检查图像是否为空..如果图像加载的是null,如果不会执行..当图像加载时完全,它会进入if条件,并将转换图像.... 是我的假设是正确还是错误? –