本文介绍了Java 将图像转换为 BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
已经有这样的问题链接 在 StackOverflow 上,接受的答案是铸造":
There is already question like this link on StackOverflow and the accepted answer is "casting":
Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;
在我的程序中,我尝试:
In my program I try:
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;
不幸的是我得到运行时错误:
Unfortunatelly I get run time error:
sun.awt.image.ToolkitImage 无法转换为 java.awt.image.BufferedImage
显然铸造不起作用.
问题是:将 Image 转换为 BufferedImage 的正确方法是什么(或是否存在)?
Obviously casting does not work.
Question is: What is (or is there) the proper way of converting Image to 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;
}
这篇关于Java 将图像转换为 BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!