java - 将图片大小调整为 100x100 大小并加载到 JLabel 中调整大小的图片中?

标签 java image resize

我使用Graphics类和drawImage()方法将图片大小调整为100x100大小。但我无法将调整大小的图像加载到 JLabel 中。是否可以将调整大小的图片加载到 JLabel 中?

Image image   =   jfc.getSelectedFile();
ImageIcon Logo   =   new ImageIcon(image.getPath());
BufferedImage resizedImage = new BufferedImage(width, height, 
BufferedImage.TYPE_INT_ARGB); 
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, 100, 100, null); // Here i resized. But after that how can i load into Jlabel?

JLabel labelLogo;
labelLogo.setIcon(Logo);
...?

最佳答案

这是一个示例:在 actionPerformed() 中修改组件后,您可能需要更新布局。

public static void main(String[] args) {
    JFrame frame = new JFrame();
    final Container panel = frame.getContentPane();
    panel.setLayout(new FlowLayout());

    // create an image an draw in it.
    final BufferedImage image = new BufferedImage(
        200, 200, BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.RED);
    g.drawLine(0, 0, image.getWidth(), image.getHeight());

    Icon iImage = new ImageIcon(image);
    // create a label with the icon.
    final JLabel label = new JLabel(iImage);
    panel.add(label);
    // create a new button.
    JButton button = new JButton("resize");
    // add an action to the button.
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // set the label with a new icon.
            BufferedImage bi = new BufferedImage(
                100, 100, BufferedImage.TYPE_INT_ARGB);
            bi.getGraphics().drawImage(image, 0, 0, null);
            label.setIcon(new ImageIcon(bi));
        }
    });
    // add the button to the frame.
    panel.add(button);
    // open the frame.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

关于java - 将图片大小调整为 100x100 大小并加载到 JLabel 中调整大小的图片中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2385249/

相关文章:

java - 如何在 linux shell 脚本中添加 java 类文件夹而不是 jar

java.io.StreamTokenizer 在遇到下划线时生成空标记

java - 如何在运行时获取 JFrame 的当前尺寸

java - 带有 HTML 的 JLabel 未正确设置宽度

java - AsyncTask 中 CookieSyncManager.createInstance 中的 NullPointerException

java - Intellij IDEA 14.1.2 拒绝保存文件

php - 如何使用 SQL Server 存储和检索图像 (Server Management Studio)

python - 使用python逐行从excel中提取图像

c++ - 使用类旋转图像

html - 如何在窗口展开时停止图像自动调整大小