Java将Image转换成BufferedImage
在StackOverflow上已经有这样的问题了,接受的答案是“cast”:
Image image = ImageIO.read(new File(file)); BufferedImage buffered = (BufferedImage) image;
在我的程序中,我尝试:
final float FACTOR = 4f; BufferedImage img = ImageIO.read(new File("graphic.png")); int scaleX = (int) (img.getWidth() * FACTOR); int scaleY = (int) (img.getHeight() * FACTOR); Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH); BufferedImage buffered = (BufferedImage) image;
不幸的是我得到运行时错误:
sun.awt.image.ToolkitImage不能转换为java.awt.image.BufferedImage
显然铸造不起作用。
问题是:什么是(或有)正确的方式转换图像到BufferedImage?
从Java游戏引擎 :
/** * Converts a given Image into a BufferedImage * * @param img The Image to be converted * @return The converted BufferedImage */ public static 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; }
处理这种情况的一种方法是创build一个新的BufferedImage,并告诉它的graphics对象将缩放的图像绘制到新的BufferedImage中:
final float FACTOR = 4f; BufferedImage img = ImageIO.read(new File("graphic.png")); int scaleX = (int) (img.getWidth() * FACTOR); int scaleY = (int) (img.getHeight() * FACTOR); Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH); BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE); buffered.getGraphics().drawImage(image, 0, 0 , null);
这应该做的伎俩,而不是铸造。
如果你找回了一个sun.awt.image.ToolkitImage
,你可以把Image转换成这个,然后使用getBufferedImage()来获得BufferedImage
。
所以,而不是你最后一行代码,你只是做:
BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();