2012-07-24 192 views
1

我正在使用下面的代码在摆动框架上显示图像。如何将java swing的ImageIcon图像保存到文件?

ImageIcon icon = new ImageIcon("image.jpeg"); 
icon.getImage().flush(); 
jLabel3.setIcon(icon); 

我需要一个按钮,当点击时将保存带有jpeg/png扩展名的图像。

+0

大家好,欢迎SO形象!请考虑查看问题编辑器,了解工具栏中的不同按钮可以为您做什么 - 例如将您的代码格式化为更易于理解的格式。 =)你有什么特别的问题?你试过了什么,问题在哪里? – 2012-07-24 07:45:40

回答

7

我平时做这样的事情

Image img = icon.getImage(); 

BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_BYTE_ARGB); 

Graphics2D g2 = bi.createGraphics(); 
g2.drawImage(img, 0, 0, null); 
g2.dispose(); 
ImageIO.write(bi, "jpg", new File("img.jpg")); 

也尝试其他图像类型,如BufferedImage.TYPE_INT_RGB,结账BufferedImage

您可能还需要阅读本Writing/Saving an Image

希望对你有用

0

考虑使用ImageIO.write(Image img, String type, File file)将图像写入文件系统。

你从ImageIcon的Image对象与getImage()

您必须实现的按钮的ActionListener,然后就准备去

+1

类型ImageIO中的方法write(RenderedImage,String,File)不适用于参数(图像,字符串,文件) – TomSelleck 2013-04-14 16:20:49

+0

尝试将图像转换为RenderedImage - 应该工作 - 或者将其重新绘制为新的Buffered图像, Leon在他的回答中提到 – itshorty 2013-04-17 10:13:01

0

因此,第一个部分是实现的ActionListener使按键作品当你点击它。 JButton。

第二部分是节省,我用ImageIo.write

见下面的代码

public class MyFrame extends JFrame implements ActionListener { 
    private JButton button1 = new JButton("Click me!"); 


    public MyFrame() { 
    button1.addActionListener(this); 

    //... add buttons to frame ... 
    } 

    public void actionPerformed(ActionEvent evt) { 
    Object src = evt.getSource(); 
    if (src == button1) { 
     string imagename = icon.getDescription; 


     try { 
    // retrieve image 
    BufferedImage bi = icon.getImage(); 
    File outputfile = new File("saved.png"); 
    ImageIO.write(bi, "png", outputfile); 
} catch (IOException e) 


{ 
     //catch the exception here 
    } 
    } 
    } 
} 
+1

BufferedImage bi = icon.getImage(); < - “类型不匹配:无法从图像转换为BufferedImage” – TomSelleck 2013-04-14 16:18:54

+0

BufferedImage bi = icon.getImage(); 您将得到“java.lang.ClassCastException:sun.awt.image.ToolkitImage无法转换为java.awt.image.BufferedImage” – Sanoop 2016-02-09 16:58:30