Reputation:
Hello I have problem with followed function that should save forwarded bufferedImage on disk. When I run this code there no exception throwed no problems, BufferedImage is transfered to ImageIO.write(img, ext ,fileToSave) file was created, ext is correct but there no image on my disk! After hours i dont have idea what can go wrong. Maybe permission? But i have it to read/write on disk.
public boolean SaveImage(BufferedImage img)
{
JFileChooser FC=new JFileChooser("C:/");
FC.addChoosableFileFilter(new jpgSaveFilter());
FC.addChoosableFileFilter(new jpegSaveFilter());
FC.addChoosableFileFilter(new PngSaveFilter());
FC.addChoosableFileFilter(new gifSaveFilter());
FC.addChoosableFileFilter(new BMPSaveFilter());
FC.addChoosableFileFilter(new wbmpSaveFilter());
int retrival=FC.showSaveDialog(null);
if (retrival == FC.APPROVE_OPTION)
{
String ext="";
String extension=FC.getFileFilter().getDescription();
if(extension.equals("*.jpg,*.JPG"))
{
ext=".jpg";
}
if(extension.equals("*.png,*.PNG"))
{
ext=".png";
}
if(extension.equals("*.gif,*.GIF"))
{
ext=".gif";
}
if(extension.equals("*.wbmp,*.WBMP"))
{
ext=".wbmp";
}
if(extension.equals("*.jpeg,*.JPEG"))
{
ext=".jpeg";
}
if(extension.equals("*.bmp,*.BMP"))
{
ext=".bmp";
}
File fileToSave = FC.getSelectedFile();
try{
ImageIO.write(img, ext ,fileToSave);
}
catch (IOException e) {
e.printStackTrace();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
return false;
}
return true;
}
return false;
}
Thanks for help!
Upvotes: 2
Views: 3558
Reputation: 68907
Extensions in ImageIO.write should be like "PNG"
, "JPG"
. without the point.
And the if (extension.equals("..."))
approach is very bad. Make sure you actually provided an extension. IE: at least one of the if's succeeded. Try to print the ext
just before writing, to check if it has a correct value.
System.out.println("Extension: " + ext);
Oh, and javax.imageio
only supports PNG, JPG, JPEG (and GIF read-only). To get dynamically a list of supported formats, use:
ImageIO.getWriterFormatNames();
Upvotes: 2
Reputation: 11
mistake may be here: JFileChooser FC=new JFileChooser("C:/"); change the file path to "C:\" (or double backslash)
Upvotes: 0
Reputation: 347334
The problem is your specifying the file format as the ext
Effectively your saying
ImageIO.write(img, ".jpg" ,fileToSave)
You need to supply it so it evaluates to
ImageIO.write(img, "jpg" ,fileToSave)
Upvotes: 5