Java将图像转换为BufferedImage [英] Java converting Image to BufferedImage
本文介绍了Java将图像转换为BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
已有类似这样的问题 link
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我遇到运行时错误:
Unfortunatelly I get run time error:
sun.awt.image.ToolkitImage无法投射到java.awt.image.BufferedImage
sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
问题是:将图像转换为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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!