java 如何将java swing ImageIcon图像保存到文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11626307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to save java swing ImageIcon image to file?
提问by sky
I am using the following code for displaying the Image on the swing frame.
我正在使用以下代码在摆动框架上显示图像。
ImageIcon icon = new ImageIcon("image.jpeg");
icon.getImage().flush();
jLabel3.setIcon( icon );
I need a button which when clicked upon will save the image with a jpeg/png extension .
我需要一个按钮,单击该按钮时将使用 jpeg/png 扩展名保存图像。
回答by Leon
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
还可以尝试其他图像类型,如 BufferedImage.TYPE_INT_RGB,结帐BufferedImage
you may also want to read this Writing/Saving an Image
您可能还想阅读此写作/保存图像
hope it works for you
希望对你有帮助
回答by itshorty
consider useing ImageIO.write(Image img, String type, File file)for writeing a Image to the filesystem.
考虑使用ImageIO.write(Image img, String type, File file)将图像写入文件系统。
You get an Image object from the ImageIcon with getImage()
你从 ImageIcon 得到一个 Image 对象 getImage()
You have to Implement a ActionListener for the Button, and then you are ready to go
你必须为 Button 实现一个 ActionListener,然后你就可以开始了
回答by Frank Visaggio
So the first part is implementing actionlistener so the button works when you click it. The JButton.
所以第一部分是实现 actionlistener,所以当你点击它时按钮会起作用。J按钮。
The second part is saving the image which i use ImageIo.write
第二部分是保存我使用 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
}
}
}
}