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 ?
Just use the read method of the Java ImageIO class, and you can open/read images in a variety of formats (GIF, JPG, PNG) in basically one line of Java code.
The ImageIO. write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats. But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.
ImageIO. A class containing static convenience methods for locating ImageReader s and ImageWriter s, and performing simple encoding and decoding. ImageReader. An abstract superclass for parsing and decoding of images.
Remove the .
from your format name.
ImageIO.write(buff, "jpg", new File(savePath));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With