Java的转换图像设置为BufferedImage(Java converting Image to

2019-06-21 08:02发布

已经有这样的质疑链接 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不能转换为java.awt.image.BufferedImage中

显然,铸造不起作用。
问题是:什么是(或有)转换图像到BufferedImage的正确方法?

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


Answer 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);

这应该做的伎俩没有铸造。



Answer 3:

如果您收到回sun.awt.image.ToolkitImage ,你可以投出的图像到,然后用getBufferedImage()来获得BufferedImage

因此,而不是代码的最后一行,你是铸造你只是做:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();


Answer 4:

如果您使用的科特林,你可以以同样的方式斯里兰卡戒Chilakapati建议添加一个扩展方法的图像。

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()


文章来源: Java converting Image to BufferedImage