我尝试了很多方法在Applet程序中将Image类的图像转换为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 :(得分: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);
〜问候Max