2011-05-05 132 views
13

我有一个PNG图像,我想调整它的大小。我该怎么做?虽然我已经通过this我无法理解片段。在java中调整大小图像

+0

你究竟对这段代码不了解? – Heisenbug 2011-05-05 10:02:55

+0

你想生成一个原始PNG的调整大小的版本,或者只是在你的用户界面的某处绘制一个调整大小的版本? – dcn 2011-05-05 10:03:51

+0

@ dcn resized version – 2011-05-05 10:35:45

回答

38

如果你有一个Image,rezising它不需要任何额外库。只要做到:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT); 

Ovbiously,具有指定图像的尺寸更换newWidthnewHeight
注意最后一个参数:它告诉运行时您要用于调整大小的算法

有算法可以产生非常精确的结果,但是这些算法需要很长时间才能完成。
您可以使用任何的算法如下:

查看Javadoc了解更多信息。

+1

文档链接指的是旧版本使用它来代替:http://download.oracle.com/javase/6/docs/api/java/awt/Image.html – 2011-05-05 10:57:12

+0

@哈里乔伊:你说得对。我会编辑我的答案。谢谢! – 2011-05-05 18:42:11

4

试试这个:

ImageIcon icon = new ImageIcon(UrlToPngFile); 
Image scaleImage = icon.getImage().getScaledInstance(28, 28,Image.SCALE_DEFAULT); 
+2

IIRC,这种方式(getSclaedInstance())由于缺乏性能而不被建议(我认为很久以前,我在“肮脏的富客户端”中阅读过)。 – jfpoilpret 2011-05-05 10:22:12

+5

@jfpoilpret:欲了解更多信息。看[Image.getScaledInstance()]的危害(http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html)。 – 2011-05-05 10:37:02

+0

不需要使用'ImageIcon',你可以直接执行'ImageIO.read(...)'。 – 2011-05-07 14:59:52

7

我们这样做是为了创建图像的缩略图:

BufferedImage tThumbImage = new BufferedImage(tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB); 
    Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to 
    tGraphics2D.setBackground(Color.WHITE); 
    tGraphics2D.setPaint(Color.WHITE); 
    tGraphics2D.fillRect(0, 0, tThumbWidth, tThumbHeight); 
    tGraphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
    tGraphics2D.drawImage(tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null); //draw the image scaled 

    ImageIO.write(tThumbImage, "JPG", tThumbnailTarget); //write the image to a file