2017-05-09 158 views
0

我通過作物意圖在SD卡中保存了一個位圖文件,我想在另一個活動中讀取它。但是,我一直收到以下運行時錯誤:無法解碼流:java.io.FileNotFoundException:file:/sdcard/oc.jpg:打開失敗:ENOENT(沒有這樣的文件或目錄) E/ReadFile:位圖必須爲非-null從SD卡讀取位圖

Uri uri=Uri.parse("file:///sdcard/oc.jpg"); 
//save output image in uri 
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 

讀同一文件中的另一活動:

Bitmap image4 = BitmapFactory.decodeFile("file:///sdcard/oc.jpg"); 

我試圖this solution但它沒有工作,我得到了相同的運行時間錯誤。

+0

「我通過作物意圖在SDcard中保存了一個位圖文件」 - [Android沒有'CROP''Intent'](https://commonsware.com/blog/2013/01/23/no -Android-不 - 不具備的,作物intent.html)。 「無法解碼流:java.io.FileNotFoundException:file:/sdcard/oc.jpg」 - 不要硬編碼路徑(使用方法,像'Environment.getExternalStorageDirectory()'),並確保您有適當的權限(包括運行時權限)。 – CommonsWare

+0

我試過String imageInSD = Environment.getExternalStorageDirectory()。getAbsolutePath()+「oc.jpg」; image4 = BitmapFactory.decodeFile(imageInSD);但仍然無法讀取位圖,並且包含運行時權限 – MKH

+0

'.... getAbsolutePath()+「oc.jpg」'應該是'.getAbsolutePath()+「/ oc.jpg」' – greenapps

回答

0

你需要寫外部存儲,請確保您添加的權限:

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

檢查,如果外部存儲空間可用於讀取和寫入

public boolean isExternalStorageWritable() { 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     return true; 
    } 
    return false; 
} 

使用root的公共目錄而不是使用Android的根目錄。

如果你想保存在外部存儲公用文件,使用getExternalStoragePublicDirectory()

public File getAlbumStorageDir(String albumName) { 
    // Get the directory for the user's public pictures directory. 
    File file = new File(Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_DCIM), albumName); 
    if (!file.mkdirs()) { 
     Log.e(LOG_TAG, "Directory not created"); 
    } 
    return file; 
} 

如果你想保存僅對您的應用程序文件,使用getExternalFilesDir()

public File getAlbumStorageDir(Context context, String albumName) { 
    // Get the directory for the app's private pictures directory. 
    File file = new File(context.getExternalFilesDir(
      Environment.DIRECTORY_DCIM), albumName); 
    if (!file.mkdirs()) { 
     Log.e(LOG_TAG, "Directory not created"); 
    } 
    return file; 
} 

,我忘了提:

decodeFile預計的路徑