java - 如何调整 Jlabel ImageIcon的大小?

我正在制作一个Java Swing应用程序(实际上是一个MigLayout ):


[icon][icon][icon][....]
where icon = jlabel and the user can add more icons

问题非常简单:我有一个包含JLabel的ImageIcon,如何调整此图标的大小?

时间:

调整图标大小并不简单,你需要使用java graphics 2D,然后缩放图像,第一个参数是一个图像类,你可以很容易地从ImageIcon类获得,可以使用ImageIcon类加载图像文件,然后简单地调用getter方法来获取图像。


 private Image getScaledImage(Image srcImg, int w, int h){
 BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
 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;
}

尝试这个:


ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way 
imageIcon = new ImageIcon(newimg); // transform it back

调整图像大小的一种(快速这甚至适用于有透明度的动画图像。

此代码可以工作,调整ImageIcon的大小,同时保持纵横比。


/*
 * source File of image, maxHeight pixels of height available, maxWidth pixels of width available
 * @return an ImageIcon for adding to a label
 */


public ImageIcon rescaleImage(File source,int maxHeight, int maxWidth)
{
 int newHeight = 0, newWidth = 0; // Variables for the new height and width
 int priorHeight = 0, priorWidth = 0;
 BufferedImage image = null;
 ImageIcon sizeImage;

 try {
 image = ImageIO.read(source); // get the image
 } catch (Exception e) {

 e.printStackTrace();
 System.out.println("Picture upload attempted & failed");
 }

 sizeImage = new ImageIcon(image);

 if(sizeImage != null)
 {
 priorHeight = sizeImage.getIconHeight(); 
 priorWidth = sizeImage.getIconWidth();
 }

 // Calculate the correct new height and width
 if((float)priorHeight/(float)priorWidth > (float)maxHeight/(float)maxWidth)
 {
 newHeight = maxHeight;
 newWidth = (int)(((float)priorWidth/(float)priorHeight)*(float)newHeight);
 }
 else 
 {
 newWidth = maxWidth;
 newHeight = (int)(((float)priorHeight/(float)priorWidth)*(float)newWidth);
 }


 // Resize the image

 // 1. Create a new Buffered Image and Graphic2D object
 BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
 Graphics2D g2 = resizedImg.createGraphics();

 // 2. Use the Graphic object to draw a new image to the image in the buffer
 g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
 g2.drawImage(image, 0, 0, newWidth, newHeight, null);
 g2.dispose();

 // 3. Convert the buffered image into an ImageIcon for return
 return (new ImageIcon(resizedImg));
}

...