我用java编写一个图片生成器但是无法保存?我想问一下怎样才能保存啊?有没有代码啊?拜托了,急需
1个回答
展开全部
你是想要保存图片么?可以看下下面的代码,从一个项目中截取的片断,其中image是BufferedImage类型的
private void saveAs()
{
if(image != null)
{
JFileChooser jfc=new JFileChooser(".");
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter1 = new FileNameExtensionFilter("*.png", "png");
FileNameExtensionFilter filter2 = new FileNameExtensionFilter("*.jpg", "jpg");
FileNameExtensionFilter filter3 = new FileNameExtensionFilter("*.jpeg", "jpeg");
jfc.addChoosableFileFilter(filter1);
jfc.addChoosableFileFilter(filter2);
jfc.addChoosableFileFilter(filter3);
jfc.setAcceptAllFileFilterUsed(false);
jfc.setFileFilter(filter1);
jfc.setSelectedFile(new File("2D_Code"));
int returnVal = jfc.showSaveDialog(MainFrame.this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = jfc.getSelectedFile();
String tmp = jfc.getFileFilter().getDescription();
String imgType = tmp.substring(tmp.lastIndexOf(".") + 1, tmp.length());
String filename = file.getPath() + "." + imgType;
file = new File(filename);
if(file.exists())
{
int i = JOptionPane.showConfirmDialog(this, "File exists! Overwrite it?","Attention",JOptionPane.OK_OPTION);
if(i != JOptionPane.OK_OPTION)
return;
}
try {
ImageIO.write(image, imgType, file);
JOptionPane.showMessageDialog(this, "Successfully saved!");
} catch (IOException e1) {
JOptionPane.showMessageDialog(this, "Failed saving.");
e1.printStackTrace();
}
}
}
else
{
JOptionPane.showMessageDialog(this, "No image generated!");
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询