我試圖從設備的內部和外部存儲器中添加圖像到我的應用程序。我能夠打開畫廊的意圖,並獲得文件的路徑,但我無法將其轉換爲我的ImageView的位圖。 這裏是導出代碼爲的onClick偵聽器的圖標調用庫:Android從內部/外部存儲器選擇圖像
icoGallery = (ImageView) findViewById(R.id.icoGallery);
icoGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
}
});
下面是onActivitResult代碼:我已經包括以下權限清單
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null !=data){
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
@SuppressWarnings("deprecation")
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
cursor.moveToFirst();
int column_index = cursor.getColumnIndex(projection[0]);
imagePath = cursor.getString(column_index);
cursor.close();
imageFile = new File(imagePath);
if (imageFile.exists()){
Bitmap imageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
imgPhoto.setImageBitmap(imageBitmap);
}
} else {
Toast.makeText(context, "You have not selected and image", Toast.LENGTH_SHORT).show();
}
}
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
我總是收到以下錯誤
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/20170215_152240.jpg: open failed: EACCES (Permission denied)
我相信它失敗的部分原因是因爲該設備只有內部存儲。有沒有辦法從本地存儲設備或外部設備添加圖像?或者我必須提出一個功能,詢問用戶是否想使用內部或外部存儲器?
感謝提前:)
編輯: 的錯誤是由未初始化的ImageView引起的。但是,從Gallery活動返回並返回文件的路徑後,圖像不會顯示在ImageView上。它更改爲背景顏色。
你是在模擬器上運行?如果不是,請嘗試在實際設備中運行,並從您的電腦中取出USB連接。 – noahutz
我正在測試一個實際的設備。仍然沒有變化 –
您正在運行的設備的版本是什麼?我猜測它是Android 6.0。如果是這樣,那是因爲您需要啓用運行時權限。嘗試使用Android 6.0之前的設備,並查看您的代碼是否正常工作。 – noahutz