2016-09-07 81 views
0

我現在正在處理一個奇怪的事情。我的代碼曾經工作到幾天前停止工作。 我正在從圖庫中選擇一幅圖像,並希望獲取它的位圖對象。 我的代碼:BitmapFactory解碼返回null

imgDecodableString = "/storage/emulated/0/DCIM/Camera/IMG_20160114_141351594.jpg" 

Bitmap decodedBitmap = BitmapFactory.decodeFile(imgDecodableString); 
Log.d(Constants.TAG, "decodedBitmap: " + decodedBitmap); 

位圖現在是空(用於工作),我真的不明白什麼是錯的。沒有改變我的代碼。有沒有人有這個問題?謝謝。

我有權限:

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

如果您使用的Android 6.0比你需要運行時寫入外部存儲 –

回答

1
if (CheckPermission(youractivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { 
// you have permission go ahead 

String imgDecodableString = "/storage/emulated/0/DCIM/Camera/IMG_20160114_141351594.jpg"; 

if(new File(imgDecodableString).exists()){ 
Bitmap decodedBitmap = BitmapFactory.decodeFile(imgDecodableString); 
Log.d("Tag", "decodedBitmap: " + decodedBitmap);} 
} else { 
// you do not have permission go request runtime permissions 
RequestPermission(youractivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_RUNTIME_PERMISSION); 
} 



@Override 
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) { 

    switch (permsRequestCode) { 

     case REQUEST_RUNTIME_PERMISSION: { 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

      } else { 
       // you do not have permission show toast. 
      } 
      return; 
     } 
    } 
} 
public void RequestPermission(Activity thisActivity, String Permission, int Code) { 
    if (ContextCompat.checkSelfPermission(thisActivity, 
      Permission) 
      != PackageManager.PERMISSION_GRANTED) { 
     if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, 
       Permission)) { 

     } else { 
      ActivityCompat.requestPermissions(thisActivity, 
        new String[]{Permission}, 
        Code); 
     } 
    } 
} 

public boolean CheckPermission(Activity context, String Permission) { 
    if (ContextCompat.checkSelfPermission(context, 
      Permission) == PackageManager.PERMISSION_GRANTED) { 
     return true; 
    } else { 
     return false; 
    } 
} 

在androidmainfest

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

您需要刪除從第一線的意見,就應該是這樣的

imgDecodableString = "/storage/emulated/0/DCIM/Camera/IMG_20160114_141351594.jpg" 

Bitmap decodedBitmap = BitmapFactory.decodeFile(imgDecodableString); 
Log.d(Constants.TAG, "decodedBitmap: " + decodedBitmap); 
0

,請使用以下代碼:

if(imgDecodableString.exists()){ 
Bitmap decodedBitmap = BitmapFactory.decodeFile(imgDecodableString); 
Log.d(Constants.TAG, "decodedBitmap: " + decodedBitmap);} 

希望它會有所幫助。

+0

嗨的許可,感謝,但您是否使用棉花糖版本肯定:) – user1140656

+0

圖像存在? – Yogendra