Java 如何获取缓冲图像的缩放实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19506927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:50:39  来源:igfitidea点击:

How to get scaled instance of a bufferedImage

javascalebufferedimagetoolkit

提问by Yoda

I wanted to get scaled instance of a buffered image and I did:

我想获得缓冲图像的缩放实例,我做到了:

public void analyzePosition(BufferedImage img, int x, int y){   
     img =  (BufferedImage) img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
....
}

but I do get an exception:

但我确实得到了一个例外:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
    at ImagePanel.analyzePosition(ImagePanel.java:43)

I wanted then to cast to ToolkitImagethen use the method getBufferedImageI read about in other articles. The problem is there is no class such as sun.awt.image.ToolkitImageI cannot cast to it because Eclipse does not even see this class. I use Java 1.7and jre1.7.

然后我想转换ToolkitImage然后使用getBufferedImage我在其他文章中读到的方法。问题是没有诸如sun.awt.image.ToolkitImage我无法转换的类,因为 Eclipse 甚至看不到这个类。我使用Java 1.7jre1.7

enter image description here

在此处输入图片说明

采纳答案by Hovercraft Full Of Eels

You can create a new image, a BufferedImage with the TookitImage.

您可以使用 TookitImage 创建一个新图像,一个 BufferedImage。

Image toolkitImage = img.getScaledInstance(getWidth(), getHeight(), 
      Image.SCALE_SMOOTH);
int width = toolkitImage.getWidth(null);
int height = toolkitImage.getHeight(null);

// width and height are of the toolkit image
BufferedImage newImage = new BufferedImage(width, height, 
      BufferedImage.TYPE_INT_ARGB);
Graphics g = newImage.getGraphics();
g.drawImage(toolkitImage, 0, 0, null);
g.dispose();

// now use your new BufferedImage

回答by MadProgrammer

BufferedImage#getScaledInstanceis actually inherited from java.awt.Imageand only guarantees that it will return an Imageso I would say it's not a good idea to try and assume the underlying return type in this case.

BufferedImage#getScaledInstance实际上是继承自java.awt.Image并且只保证它会返回 anImage所以我会说在这种情况下尝试假设底层返回类型不是一个好主意。

getScaledInstanceis, also, not normally the fastest or best quality method

getScaledInstance也不是通常最快或质量最好的方法

To scale a BufferedImageitself, you have a number of different options, but most simply take the original and repaint it to another image, applying some kind of scaling in process.

要缩放一个BufferedImage本身,您有许多不同的选择,但大多数只是简单地将原始图像重新绘制到另一个图像上,在过程中应用某种缩放。

For example:

例如:

For more details about getScaledInstance, have a read of The Perils of Image.getScaledInstance()

有关 的更多详细信息getScaledInstance,请阅读Image.getScaledInstance() 的危险