ImageIO cannot write buffered image to file

I am having trouble writing a bufferedimage file in a file jpg. in my method, I get a parameter bufferedimagethat I need to write to the file -

that's what I'm 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 is printed 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

works fine without any exceptions, but the generated jpg file size is 0 bytes

I tried to record an 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 it works absolutely fine.

Why doesn't it work with ImageIO?

+5
source share
2 answers

Remove .the format from your name.

ImageIO.write(buff, "jpg", new File(savePath));
+8
source

, ".jpg", "jpg", .

, ImageIO .

+4

All Articles