如何从JLabel保存图像 [英] How to save an Image from a JLabel

查看:98
本文介绍了如何从JLabel保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个GUI,该GUI将保存用户在JLabel上绘制的图像.这是我的saveImage方法的代码.我可以弹出框,以便选择保存文件的位置,但实际上没有保存任何文件.

I am working to create a GUI that will save an Image drawn on a JLabel by a user. Here is the code that I have for my saveImage method. I can get the box to pop up so that I can select where to save the file, but no file is actually saved.

public void saveImage()
    {
        BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D image2 = image.createGraphics();
        image2.setBackground(Color.WHITE);
        image2.clearRect(0, 0, this.getWidth(), this.getHeight());
        this.paintAll(image2);
        try
        {
            File output = new File("rectangle.png");
            ImageIO.write(image, "Rectangles", output);
            final JFileChooser fchooser = new JFileChooser(".");
            int retvalue = fchooser.showSaveDialog(RectangleLabel.this);
            if (retvalue == JFileChooser.APPROVE_OPTION)
            {
                fchooser.setSelectedFile(output);
                File f = fchooser.getSelectedFile();
            }
        }
        catch(IOException ie)
        {

        }


    }

推荐答案

首先,您需要创建组件的图像...

First, you need to create an image of the component...

 BufferedImage img = new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);
 Graphics2D g2d = img.createGraphics();
 label.printAll(g2d);
 g2d.dispose();

然后您需要保存它...

Then you need to save it...

 ImageIO.write(img, "png", f);

看看编写/保存图像更多详情

这篇关于如何从JLabel保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆