如何在 Swing 中调整图像大小?

How to Resize an Image in Swing?

我已经学习了很多次如何在 Javax swing 中添加图像。 我用过容器和所有图像图标,但问题是我的照片太大,放不下。它们的尺寸超过 1800*1700 像素,屏幕显然无法容纳它们。 我会请你们提出一种缩小图像的方法。仅供参考,我已经尝试了其中的大部分方法,例如使用 awt Image、setBounds、SCALE_DEFAULT 等。 出于某种原因,我的 IDE,BlueJ 似乎无法使用建议的许多方法,但我仍然会请求您帮助我。 这是代码:

import javax.swing.*;
import java.awt.*;


class JLabelDemo
{
public JLabelDemo()
{
    JFrame jfrm=new JFrame("Image from book");
    jfrm.setLayout(new FlowLayout());
    jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
    jfrm.setSize(500,700);
    
    ImageIcon ii=new ImageIcon("D:\Dhruv Rana\UNATIS Mandarmoni Trip\Sunrise.jpg");
    JLabel jl=new JLabel("Background",ii,JLabel.CENTER);
    jfrm.add(jl);
    jfrm.setVisible(true);
}
public static void main(String [] args)
{
    SwingUtilities.invokeLater(
    new Runnable()
    {
        public void run()
        {
            new JLabelDemo();
        }
    }
    );
}
}

将其放入缓冲图像

Graphics2D grph = image.createGraphics();
grph.scale(2.0, 2.0);
grph.dispose();

或者看看How to scale a BufferedImage

我想这取决于您是否要维护加载到 JLabel 中的图像的 Aspect Ratio

无论如何,下面是一个考虑了宽高比的可运行文件,这样图像在显示时看起来就不会失真(拉长等)。 JFrame window 会根据图像纵横比自动调整大小,以便根据要显示的图像在纵向或横向中保持所需的窗体大小。如果图像是纵向格式,那么 JFrame window 也是。如果图像是横向格式,那么将 JFrame window.

两种有趣的方法是 resizeImageIcon()getAspectRatioDimension() 方法。请务必阅读代码中的注释。

代码如下:

import java.awt.*;
import javax.swing.*;

public class JLabelDemo {

    public JLabelDemo() {
        int figNum = 1;     // Image figure number (optional)
        // Load in the Image
        ImageIcon ii = new ImageIcon("D:\Dhruv Rana\UNATIS Mandarmoni Trip\Sunrise.jpg");
        
        /* Get the Aspect Ratio of the image in relation to the 
           desired size of JFrame form (500 x 700)        */
        java.awt.Dimension aspectDimensions = getAspectRatioDimension(
                           ii.getIconWidth(), ii.getIconHeight(), 500, 700);
        
        // Create the Window
        JFrame jfrm = new JFrame("Image from book");
        jfrm.setLayout(new FlowLayout());
        jfrm.setAlwaysOnTop(true);  // Form will always be on top of other wondows.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        /* Set the form's size in accordance to the Aspect Ratio.
           40 is added to the hieght so as to accommodate for the
           JLabel text.        */
        jfrm.setSize(aspectDimensions.width, aspectDimensions.height + 40);
        jfrm.setResizable(false); // Make form non-sizable
        
        /* Resise the image in accordance to the Aspect Ratio
           less 30 so as not to hug the edge of Window.    */
        ii = resizeImageIcon(ii, aspectDimensions.width - 30, aspectDimensions.height - 30);
        
        // Create the JLabel and apply the image
        JLabel jl = new JLabel("", ii, JLabel.CENTER);
        
        // Un-comment if you want a border on the JLabel.
        //jl.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
        
        // Set the JLabel text below the Image and at center.
        jl.setVerticalTextPosition(JLabel.BOTTOM);
        jl.setHorizontalTextPosition(JLabel.CENTER);
        
        // Provide the JLabel text (basic HTML is used here to add a little pizaze) 
        jl.setText("<html><font size='2' color=gray><i>Figure " + figNum + ":&nbsp;&nbsp; Background</i></font></html>");
        
        jfrm.add(jl);
        jfrm.pack();
        jfrm.setLocationRelativeTo(null);   // Set window to center Screen.
        jfrm.setVisible(true);              // Display Window
        
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JLabelDemo();
            }
        });
    }
    
    public static javax.swing.ImageIcon resizeImageIcon(javax.swing.ImageIcon icon, int resizedWidth, int resizedHeight) {
        java.awt.Image img = icon.getImage();
        java.awt.Image resizedImage = img.getScaledInstance(resizedWidth, resizedHeight, java.awt.Image.SCALE_SMOOTH);
        return new javax.swing.ImageIcon(resizedImage);
    }
    
    /**
     * This method will retrieve the required dimensions in order to maintain
     * the aspect ratio between the original dimensions and the desired
     * dimensions.<br><br>
     * <p>
     * <b>Example Usage:</b><pre>
     *
     *          Dimension dim = getAspectRatioDimension(500, 300, 200, 200);
     *          System.out.println("Width = " + dim.width + "  ---  Height = " + dim.height);
     *          // Output will be:  Width = 200  ---  Height = 120</pre>
     *
     * @param currentWidth  (Integer) The width of current dimension to convert
     *                      from.
     * @param currentHeight (Integer) The height of current dimension to convert
     *                      from.
     * @param desiredWidth  (Integer) The width we want to convert to.
     * @param desiredHeight (Integer) The height we want to convert to.
     *
     * @return (Dimension) The actual width & height dimensions we need to
     *         maintain the Aspect Ratio from the original current dimensions.
     */
    public java.awt.Dimension getAspectRatioDimension(final int currentWidth, 
            final int currentHeight, final int desiredWidth, final int desiredHeight) {
        int original_width = currentWidth;
        int original_height = currentHeight;
        int bound_width = desiredWidth;
        int bound_height = desiredHeight;
        int new_width = original_width;
        int new_height = original_height;

        // first check if we need to scale width
        if (original_width > bound_width) {
            //scale width to fit
            new_width = bound_width;
            //scale height to maintain aspect ratio
            new_height = (new_width * original_height) / original_width;
        }

        // then check if we need to scale even with the new height
        if (new_height > bound_height) {
            //scale height to fit instead
            new_height = bound_height;
            //scale width to maintain aspect ratio
            new_width = (new_height * original_width) / original_height;
        }
        return new java.awt.Dimension(new_width, new_height);
    }
    
}