2011-11-28 790 views
0

下面的代碼從某個位置獲取圖像 - 並使該圖像壓縮圖像。 但我需要使壓縮映像成爲文件...我該怎麼做?如何將OutputStream轉換爲文件?

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. 
    } 

回答

3

image.compress已經將圖像寫入文件,假設您給出了正確的文件名。 因此,使用這樣的:

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

什麼是第一線? – quantumpotato

+2

它沒有用,現在我刪除它。 – Caner

2

由於在規定的documentation for OutputStream

大多數客戶端將使用該數據寫入文件系統(FileOutputStream中),網絡(的getOutputStream()輸出流/ getOutputStream())或內存中的字節數組(ByteArrayOutputStream)。

含義發送到OutputStream的數據已經被媒體鏈接寫入您的file

如果你的意思是,你需要訪問該文件一旦被壓縮,你應該看看documentation for the compress() method其中規定:

如果返回true,位圖可以通過傳遞一個相應的InputStream重建到BitmapFactory.decodeStream()。

所以,你需要做的是這樣的:

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