在没有JFileChooser的情况下从JLabel保存图像

时间:2018-09-04 23:04:03

标签: java swing

我想在不使用JFileChooser的情况下将图像从JLabel保存到Folder。我有这样的方法

private void SaveImage(){
        Icon icon = lblPhoto.getIcon();
        BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        ImageIcon ImageIcon = (ImageIcon)lblPhoto.getIcon();
        OutputStream out = null;
        int size =0;
        Image Image = ImageIcon.getImage();
        try {
            out = new FileOutputStream("\\RekamMedis\\Photo\\"+txtNama.getText().trim()+".jpg");
            byte[] b = new byte[size];
            out.write(b);
            ImageIO.write((RenderedImage)Image, "jpg", out);
        } 
        catch (Exception e) {
            Logger.getLogger(lblPhoto.getClass().getName()).log(Level.SEVERE, null, e);
        }
    }

但是此方法显示为空的image.jpg或其他格式。解决此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

您的代码似乎围绕着一些想法反弹,但似乎并没有实现任何目的

这个...

ImageIcon ImageIcon = (ImageIcon)lblPhoto.getIcon();

还有这个...

byte[] b = new byte[size];
out.write(b);

还有这个...

ImageIO.write((RenderedImage)Image, "jpg", out);

所有看起来都是坏主意。您不应该盲目地投射对象,我也不知道为什么要使用FileOutputStream向文件中写入一个空的字节数组(长度为0字节)。

一种更“简单”的方法是将Icon(您已经知道)涂成BufferedImage(支持RenderedImage),然后通过{{ 1}}变成ImageIO,类似...

File

我还要添加一项检查,以查看Icon icon = lblPhoto.getIcon(); BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bi.createGraphics(); icon.paintIcon(lblPhoto, g2d, 0, 0); g2d.dispose(); File file = new File("\\RekamMedis\\Photo\\"+txtNama.getText().trim()+".jpg"); ImageIO.write(bi, "jpg", file); 是否为icon,只是因为他们可能没有分配照片

相关问题