gpt4 book ai didi

Java 将 Image 转换为 BufferedImage

转载 作者:IT老高 更新时间:2023-10-28 13:52:13 25 4
gpt4 key购买 nike

已经有这样的问题 link在 StackOverflow 上,接受的答案是“casting”:

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 cannot be cast to java.awt.image.BufferedImage

显然转换不起作用。
问题是:将 Image 转换为 BufferedImage 的正确方法是什么(或是否存在)?

最佳答案

来自 Java Game Engine :

/**
* 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 将 Image 转换为 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13605248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com