1

我正在使用以下代码在摆动框架上显示图像。

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

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

4

3 回答 3

10

I usually do something like this

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"));

also try other image types like BufferedImage.TYPE_INT_RGB, checkout BufferedImage

you may also want to read this Writing/Saving an Image

hope it works for you

于 2012-07-24T08:00:52.967 回答
1

consider useing ImageIO.write(Image img, String type, File file) for writeing a Image to the filesystem.

You get an Image object from the ImageIcon with getImage()

You have to Implement a ActionListener for the Button, and then you are ready to go

于 2012-07-24T08:00:54.647 回答
-1

So the first part is implementing actionlistener so the button works when you click it. The JButton.

The second part is saving the image which i use ImageIo.write

See code below

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
    }
    } 
  }
}
于 2012-07-24T08:05:32.097 回答