Java 将图像转换为缓冲图像

2022-08-31 11:09:51

StackOverflow上已经有这样的链接,接受的答案是“铸造”:

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 不能 cast to java.awt.image.BufferedImage

显然,铸造不起作用。
问题是:将图像转换为缓冲图像的正确方法是什么(或是否存在)?


答案 1

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;
}

答案 2

处理此问题的一种方法是创建一个新的 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);

这应该可以在不施法的情况下解决问题。


推荐