2013-07-11 40 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條件,並將轉換圖像.... 是我的假設是正確還是錯誤? –