【问题标题】:How to resize the image drawn on the Panel in JavaSwing?java - 如何调整Java Swing中Panel上绘制的图像的大小?
【发布时间】:2016-10-19 23:05:39
【问题描述】:

我正在学习 JavaSwing。我想在框架上绘制一个图像,但我希望绘制的图片分辨率为 300*300。这是我在面板上绘制图像的代码。

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

class Picture 
{
    JFrame frame;
    public static void main(String[] args)
    {
        Picture poo = new Picture();
        poo.go();
    }
    private void go()
    {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.getContentPane().add(new ImageOne());
    }
    class ImageOne extends JPanel
    {
        public void paintComponent(Graphics g)
        {
            Image img = new ImageIcon("image.jpg").getImage();
            g.drawImage(img, 2, 2, this);
        }
    }
}

谁能告诉我怎么做?我搜索了网络,但我可以找到有关 BufferedImage 的解释,但我不知道如何使用它。
提前致谢。

【问题讨论】:

  • 覆盖getPreferredSize(),为example
  • @trashgod 我在class ImageOne 中使用了getPrefferedSize(),但它并没有改变任何东西。
  • 请编辑您的问题以包含minimal reproducible example,以显示您修改后的方法;还有“如果你不尊重opaque property,你可能会看到视觉伪影。”—paintComponent();另见Initial Threads
  • 1) public void paintComponent(Graphics g) 使用 @Override 表示法。 2) 任何被覆盖的paint 方法都应该以调用super 方法开始。 3) Image img = new ImageIcon("image.jpg").getImage(); 永远不要尝试在绘画方法中加载图像。在构造函数中加载它(创建一个)并将其存储为类的属性。 4) 但不要使用ImageIcon 加载图像,因为它会默默地失败。而是使用ImageIO.read(..) 5) 不要尝试将图像加载为File。它显然是应用程序的一部分。并将成为嵌入式资源。 ..
  • .. 应用程序资源在部署时将成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。6) 如果您咨询Java Docs for the Graphics API methods,您可能会注意到drawImage(..) 有许多变体,其中至少一个解决了这个问题。

标签: java image swing paintcomponent


【解决方案1】:

我相信您正在寻找 image.getScaledInstance(w,h, type)。这会将图像缩放到给定的宽度(w)和高度(h)到缩放类型。您想要使用的缩放类型是 Image.SCALE_DEFAULT。由于 getScaledInstace 的工作方式,您必须创建一个新的 BufferedImage。

所以你的代码看起来像这样

        BufferedImage img = null;
        try {
            img = ImageIO.read(new FileInputStream(new File("image.jpg")));
        } catch (Exception e) {}

        //Scale image to 300x300
        int width = 300;
        int height = 300;
        Image scaled = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);

        //Create new buffered image
        BufferedImage tempBuff = new BufferedImage(width, height, img.getType());

         // Create Graphics object
        Graphics2D tempGraph = tempBuff.createGraphics();
        // Draw the resizedImg from 0,0 with no ImageObserver then dispose
        tempGraph.drawImage(scaled,0,0,null);
        tempGraph.dispose();

        g.drawImage((Image)tempBuff, 2, 2, this);

【讨论】:

  • 我使用了你的代码,现在屏幕上没有图像。
  • 抱歉,试试这个
  • g.drawImage((Image)tempBuff, 2, 2, null); 应该是g.drawImage((Image)tempBuff, 2, 2, this);
猜你喜欢
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
相关资源
最近更新 更多