How to convert OutputStream to File?

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

The code below get image from some location - and make this image compress image. But i need to make the compress Image to be File ... How can i do it ?

   File compressFile = null;    File file = new File("MyFile");    OutputStream fOut    = new FileOutputStream(file);    if(image.compress(Bitmap.CompressFormat.PNG, 100, fOut))    {        fOut.flush();        fOut.close();        compressFile = ??? // I need here to make the OutputStream  to be back to file.     }

回答1:

image.compress already writes the image to the file, assuming you gave a correct file name. So use it like this:

   File file = new File(Environment.getExternalStorageDirectory() + "/myimage.png");    FileOutputStream fOut = new FileOutputStream(file);    image.compress(Bitmap.CompressFormat.PNG, 100, fOut);    fOut.close();


回答2:

As stated in the documentation for OutputStream:

Most clients will use output streams that write data to the file system (FileOutputStream), the network (getOutputStream()/getOutputStream()), or to an in-memory byte array (ByteArrayOutputStream).

Meaning the data sent to the OutputStream has allready been written to your file.

If what you mean is that you need access to the file once it has been compressed you should look at documentation for the compress() method which states:

If this returns true, the bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream().

So what you need to do is this:

image = BitmapFactory.decodeStream( new FileInputStream( file ) );


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!