将图像写入文件

时间:2015-11-07 20:24:23

标签: java file io

我正在尝试将缓冲的图像写入附加下一个缓冲图像字节的文件中。我有以下代码,其中引发了一些运行时异常。当我运行此代码时,我得到以下异常。为什么以及必须改变什么?

 import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.imageio.ImageIO;






    public class FileT
    {
        public static void main(String[] args)
        {   
            try {
                BufferedImage originalImage = ImageIO.read(new File("ani.jpg"));
                int i=0,c=0;
                // convert BufferedImage to byte array
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(originalImage, "jpg", baos);
                baos.flush();
                byte[] imageInByte = baos.toByteArray();
                byte[] copybuf = new byte[1024];
                baos.close();

                while(i<imageInByte.length)
                {
                    copybuf[c]=imageInByte[i];
                    c++;

                    if(i%1023==0)
                        {
                        // convert byte array back to BufferedImage
                       InputStream in = new ByteArrayInputStream(copybuf);
                       BufferedImage bImageFromConvert = ImageIO.read(in);
    ImageIO.write(bImageFromConvert, "jpg", new FileOutputStream(new File("ani1.jpg"),true));   

                        }
                        copybuf = new byte[1024];
                        i++;

             }
            }
            catch (IOException e) {
                System.out.println(e.getMessage());
            }
            }
    }
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
    at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
    at javax.imageio.ImageIO.getWriter(ImageIO.java:1592)
    at javax.imageio.ImageIO.write(ImageIO.java:1578)
    at FileT.main(FileT.java:45)

1 个答案:

答案 0 :(得分:-1)

if(i%1023==0){
// convert byte array back to BufferedImage
    InputStream in = new ByteArrayInputStream(copybuf);
    BufferedImage bImageFromConvert = ImageIO.read(in);
    ImageIO.write(bImageFromConvert, "jpg", new FileOutputStream(new File("ani1.jpg"),true));
}
copybuf = new byte[1024];
i++;

在此代码中,您可能希望将 new FileOutputStream(new File())更改为要投放到ImageOutputStream

很难从你的问题中确定你需要什么,但我认为这将解决它。如果它不只是留下评论而且我试图解决它