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; }
处理这种情况的一种方法是创建一个新的BufferedImage,并告诉它的图形对象将缩放的图像绘制到新的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();
如果你使用Kotlin,你可以像Sri Harsha Chilakapati所建议的那样向Image添加一个扩展方法。
fun Image.toBufferedImage(): BufferedImage { if (this is BufferedImage) { return this } val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB) val graphics2D = bufferedImage.createGraphics() graphics2D.drawImage(this, 0, 0, null) graphics2D.dispose() return bufferedImage }
像这样使用它:
myImage.toBufferedImage()