2013-06-01 29 views
0

在我的Android項目中,我嘗試將位圖保存到指定位置的SD卡上。壓縮位圖時的Android IOException

當我運行這個,我得到一個IOException每一次,說權限被拒絕。這是創建FileOutputStream。

這使我相信我失去了權限,但我包括READ and WRITE_EXTERNAL_STORAGE。它們在我的uses-sdk塊之前聲明,並位於應用程序塊之外。我也read/write文本到我的應用程序中的其他地方的文件,並且工作得很好。我目前的代碼已被修改爲與我在網上找到的幾種解決方案相匹配,但我無法成功保存bitmap文件。

如果有人能指出我的錯誤,我會非常感激。

ImageView imageView = (ImageView) findViewById(R.id.new_pnm_pic); 
    Bitmap bm = (Bitmap)data.getExtras().get("data"); 
    imageView.setImageBitmap(bm); 
    String outPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recruits"; 

    try { 
      File d = new File(outPath); 
      if (!d.exists()) 
      d.mkdirs(); 

      SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss"); 
      String currentTime = sd.format(new Date()); 

      File file = new File(outPath+'/'+currentTime+".jpg");    
      FileOutputStream fOut = new FileOutputStream(file.getPath()); 

      bm.compress(Bitmap.CompressFormat.JPEG, 50, fOut); 

      fOut.flush(); 
      fOut.close(); 

     } 
    catch(IOException ioe){ 
    Toast.makeText(this, "Nice try but didn't work", Toast.LENGTH_SHORT).show(); 
     } 
+0

如果使用Environment.getExternalStorageDirectory()。toString()+「Recruits」定義outPath,它會起作用嗎?我有一個getAbsolutePath()類似的問題,它解決了它。做一個日誌。在logcat中查看完整路徑。 – Opiatefuchs

+0

是否在模擬器上運行這個 – Sam

+0

我將outPath改爲 Environment.getExternalStorageDirectory()。toString()+「/ Recruits」; 和使用日誌,看看我的文件是使用以下路徑 W¯¯測試// MNT/SD卡/新兵/ 2013-06-01-17-26-50.jpg(23309) 當我試圖測試後我創建了日誌沒有顯示的FileOutputStream,這意味着這是異常。我也嘗試使用替代構造函數FileOutputStream(File),我仍然得到這個異常。 山姆:我在我的設備上運行這個 – user2442678

回答

2

改變這種

File file = new File(outPath+'/'+currentTime+".jpg"); 



File file = new File(d+'/'+currentTime+".jpg"); 

並添加權限到manifest文件: -

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 

編輯
我們開始保存圖像到SD卡之前,我們需要檢查是否sd card is mounted or not

+0

我嘗試了File的替代構造函數,它沒有改變任何東西。我的權限也很好,他們已經被檢查過,並且在我的應用程序的其他部分讀寫外部存儲沒有錯誤。 – user2442678

+0

你在模擬器上運行過嗎? – Sam

+0

沒有這是在我的設備上運行 – user2442678