2012-07-14 129 views
-1

我想保存在ImageView上顯示的位圖。我知道的是,我需要從圖像存儲位圖到SD

  1. 將位圖轉換爲流。
  2. 將該流寫入SD卡上的文件。

這裏是我做了什麼

try { 
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
        File file = new File(path, "name.png"); 
        FileOutputStream out = null; 
        if (file.exists()) { 
         // do something awesome 

        } else { 

         out = new FileOutputStream(file); 
         currentimage.compress(Bitmap.CompressFormat.PNG, 100, out); 
        } 
        out.close(); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 

我試圖更改文件名保存我明白它會在FileOutputStream中,但不能肯定

回答

0

你的代碼看起來正確的,唯一的問題是你不關閉你的OutputStream。 您需要添加

try { 
    out.close(); 
} catch (IOExcetion ex) { 
} 

它。

0

您需要通過擴展獲取到公共圖片目錄的路徑來提供文件名。

FileOutputStream out = new FileOutputStream(new File(path, "name.png")); 

或者,如果您要檢查它是否已經存在第一:

File file = new File(path, "name.png"); 
if (file.exists()) { 
    // do something awesome 
    // perhaps save over top 
    // perhaps pick another name 
} else { 
    // save it 
    FileOutputStream out = new FileOutputStream(file); 
    currentimage.compress(Bitmap.CompressFormat.PNG, 100, out); 
} 
+0

我試圖FileOutputStream中走出=新的FileOutputStream中(路徑+ 「/ test.PNG」); 。但如果我想檢查,如果圖片保存到SD卡我怎麼可以瀏覽找到它 – 2012-07-14 21:55:05

+0

是啊我有那部分處理,但由於某種原因,我無法找到圖片後,我保存在畫廊..沒有錯誤或任何其他事情 – 2012-07-14 22:02:01

+0

您需要觸發新文件的掃描。看看這裏:http://developer.android.com/reference/android/media/MediaScannerConnection.html在scanFile方法。 – 2012-07-14 22:05:51