java ImageIO 无法将缓冲图像写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11530901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:27:36  来源:igfitidea点击:

ImageIO is unable to write buffered image to file

javafilejpegjavax.imageio

提问by JAVAGeek

I am having some problem in writing bufferedimage to jpgfile. in my method , i am getting a bufferedimageas parameter which i need to write in a file-

我在将缓冲图像写入jpg文件时遇到了一些问题。在我的方法中,我得到一个bufferedimage作为参数,我需要将其写入文件-

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():

这是打印的内容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

程序运行正常,没有任何异常,但生成的jpg文件大小为 0 bytes

i tried writing image without using ImageIO :

我尝试在不使用 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 ?

为什么它不适用于 ImageIO ?

回答by cklab

Remove the .from your format name.

.从格式名称中删除。

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

回答by Rob Wagner

Believe it or not, it's just this ".jpg", change it to "jpg" and it will work fine.

信不信由你,就是这样".jpg",把它改成“jpg”就可以了。

I had the same issue, but I looked at the ImageIO, and found this link.

我遇到了同样的问题,但我查看了ImageIO,并找到了这个链接