Reputation: 2794
I am having some problem in writing bufferedimage to jpg
file.
in my method , i am getting a bufferedimage
as parameter which i need to write in a file-
here is what i am doing :
public boolean writeToFile(BufferedImage buff,String savePath) {
try {
System.out.println(buff.toString());
ImageIO.write(buff, ".jpg", new File(savePath));
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
here is what gets printed by buff.toString()
:
BufferedImage@8046f4: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 1024 height = 172 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
program runs fine without any exception, but the generated jpg file size is 0 bytes
i tried writing image without using ImageIO :
public boolean writeToFile(BufferedImage buff,String savePath) {
try {
System.out.println("got image : " + buff.toString());
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(.5f);
File file = new File(savePath);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(buff, null, null);
writer.write(null, image, iwp);
writer.dispose();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
And this works absolutely fine.
Why it is not working with ImageIO ?
Upvotes: 5
Views: 12993
Reputation: 4421
Believe it or not, it's just this ".jpg"
, change it to "jpg" and it will work fine.
I had the same issue, but I looked at the ImageIO, and found this link.
Upvotes: 4
Reputation: 3771
Remove the .
from your format name.
ImageIO.write(buff, "jpg", new File(savePath));
Upvotes: 9