java 如何缩放 BufferedImage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11367324/
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
how do I scale a BufferedImage
提问by ewok
I have viewed this question, but it does not seem to actually answer the question that I have. I have a, image file, that may be any resolution. I need to load that image into a BufferedImage
Object at a specific resolution (say, for this example, 800x800). I know the Image class can use getScaledInstance()
to scale the image to a new size, but I then cannot figure out how to get it back to a BufferedImage
. Is there a simple way to scale a Buffered Image to a specific size?
我已经查看了这个问题,但它似乎并没有真正回答我的问题。我有一个图像文件,可以是任何分辨率。我需要将该图像加载到BufferedImage
特定分辨率的对象中(例如,在本例中为 800x800)。我知道 Image 类可以getScaledInstance()
用来将图像缩放到新的大小,但是我无法弄清楚如何将它恢复为BufferedImage
. 有没有一种简单的方法可以将缓冲图像缩放到特定大小?
NOTEI I do not want to scale the image by a specific factor, I want to take an image and make is a specific size.
NOTEII 不想按特定比例缩放图像,我想拍摄图像并制作特定尺寸。
回答by alain.janinm
Something like this? :
像这样的东西?:
/**
* Resizes an image using a Graphics2D object backed by a BufferedImage.
* @param srcImg - source image to scale
* @param w - desired width
* @param h - desired height
* @return - the new resized image
*/
private BufferedImage getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
回答by Robert
You can create a new BufferedImage of the size you want and then perform a scaled paint of the original image into the new one:
您可以创建一个所需大小的新 BufferedImage,然后将原始图像按比例绘制到新图像中:
BufferedImage resizedImage = new BufferedImage(new_width, new_height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, new_width, new_height, null);
g.dispose();