Android select image from internal / external storage
I am trying to add images from both the internal and external memory of a device to my application. I am able to open the gallery intent and get the path of the file but then i am not able to convert it to a bitmap for my ImageView. Here is thecode for the onClick listener for the icon that calls the gallery:
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);
}
});
Here is the code for the 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();
}
}
I have included the following permission to the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I keep getting the following error
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/20170215_152240.jpg: open failed: EACCES (Permission denied)
I believe that part of the reason why it is failing is because the device only has internal storage. Is there a way to add an image from the device that is either on the local storage or the external one? Or do I have to make a function that asks the user if they want to use the internal or external storage?
Thanks in advance :)
EDIT: The error was caused by not initializing the ImageView. However, after coming back from the Gallery activity and returning the path of the file, the image is not displayed on the ImageView. It changes to the background color.
You can set Uri
directly to ImageView
Like this:
Uri selectedImageUri = data.getData();
imageView.setImageURI(selectedImageUri);
And then get Bitmap from ImageView:
Drawable drawable = imageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
链接地址: http://www.djcxy.com/p/67512.html
上一篇: 捕获图像并将其保存在内部存储器上
下一篇: Android从内部/外部存储中选择图像