【问题标题】:Java: Load image from file, edit and add to JPanelJava:从文件加载图像,编辑并添加到 JPanel
【发布时间】:2011-10-11 07:43:45
【问题描述】:

我想将计算机中的图像加载到 2D 图形中,以便之后可以对其进行编辑,然后我想将其添加到 JPanel。如果你需要看我的项目,我可以发给你。

void loadImage()
{

    FileDialog fd = new FileDialog(new Frame(), "Please choose a file:", FileDialog.LOAD);
    fd.show();
    if (fd.getFile() != null)
    {
        File fil = new File(fd.getDirectory(), fd.getFile());
        strDirectory = fd.getDirectory();
        strFileType = fd.getFile();
        mainImage.setIcon(new ImageIcon(fil.toString()));
        getFileList(strDirectory);
        checkFileType(strFileType);
    }
}

提前致谢

【问题讨论】:

  • 您想要实现的具体目标是什么?

标签: java image swing jlabel


【解决方案1】:

要将图像加载到内存中,您可以使用ImageIO.read(File)。之后要对其进行编辑,请通过调用 createGraphics() 从中获取 Graphics2D 实例:

BufferedImage img = ImageIO.read(yourFile);
Graphics2D g = img.createGraphics();
// Draw here on the graphics
g.dispose();

您甚至可以通过在绘制前设置 RenderingHint 来打开抗锯齿:

g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                   RenderingHints.VALUE_ANTIALIASING_ON);

然后,要将其添加到 JPanel,创建您的自定义 JComponent 并将该组件的实例添加到您的 JPanel:

public class JImageComponent extends JComponent
{
    private BufferedImage img;

    public JImageComponent(BufferedImage bi)
    {
        img = bi;
    }

    @Override
    public void paintComponent(Graphics g)
    {
        g.drawImg(img, 0, 0, this);
    }

}

【讨论】:

    【解决方案2】:

    对于图像加载,您应该使用 ImageIO 对象和方法 read(File file) see docs。然后您将获得BufferedImage 实例,您可以通过Graphics2D 实例对其进行更改,您可以通过在图像实例see docs 上调用createGraphics() 来获得该实例。最后一件事,从JPanel 或更好的JComponent see docs 覆盖方法paintComponent(),然后您可以在Graphics 实例上绘制您的图像,您将通过调用paintComponent(Graphics g) 方法获得paintComponent(Graphics g) 方法中的参数@ @ 987654324@ 其中ImageObserver 设置为null

    【讨论】:

    • 不要覆盖paint(...),而是覆盖paintComponent(...)
    【解决方案3】:

    请阅读有关Icon in Swing 的教程,您的Image/ImageIcon 将被放置到JLabel,这样就消除了所有来自paint/paintComponents 的麻烦...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      相关资源
      最近更新 更多