I am asking the user for the access to the gallery through the code as a listener here:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
However, I am confused as to how I would set a variable to the photo selected.
Where would I put the code to set a variable as the photo selected?
Thanks :)
First you have to override onActivityResult to get the uri of the file selected image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == SELECT_PHOTO) {
if (resultCode == RESULT_OK) {
if (intent != null) {
// Get the URI of the selected file
final Uri uri = intent.getData();
useImage(uri);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
Then define useImage(Uri) to use the image
void useImage(Uri uri)
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
//use the bitmap as you like
imageView.setImageBitmap(bitmap);
}
You can do it like this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
Alternative for Akash Kurian Jose answer
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
I always use
fun getBitmap(file: Uri, cr: ContentResolver): Bitmap?{
var bitmap: Bitmap ?= null
try {
val inputStream = cr.openInputStream(file)
bitmap = BitmapFactory.decodeStream(inputStream)
// close stream
try {
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}catch (e: FileNotFoundException){}
return bitmap
}
It works both for photos from gallery and photos from camera.
Larger issue about it: Picasso unable to display image from Gallery
Open Gallery using this method:
private void openGallery(){
if (Build.VERSION.SDK_INT <19){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)),GALLERY_INTENT_CALLED);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
}
}
Then you are able to read convert Uri to Bitmap using afromentioned ContentResolver.openInputStream or set image ImageView.setImageUri(Uri)
If you want to display the selected image to any particular ImageView.
Suppose we have RC_PHOTO_PICKER = 1 then these lines of code should do the magic
private void openPhotoPicker() {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Complete Action Using"), RC_PHOTO_PICKER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
//set the selected image to ImageView
mImageView.setImageURI(pickedImage);
}
}
And simply call the openPhotoPicker() method afterwards
Related
I'm trying to open an image using intent.
The path of the image in my storage is /storage/emulated/0/nitp/download/logo.png.
My code is
Intent intent = new Intent();
intent.setAction(Intent.ACTION_DEFAULT);
intent.setDataandType(Uri.parse("/storage/emulated/0/nitp/download/logo.png"),"image/*");
startActivity(intent);
I also tried putting file://storage/emulated/0/nitp/download/logo.png
and content://storage/emulated/0/nitp/download/logo.png
What is the path I should use?
Solved
Have to use file:///storage/emulated/0/nitp/downloads/logo.png
For Pick image from media Storage or SD Card:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
And For get the path of Image and set in ImageView:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
imgpath= MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageViewProfileImage.setImageBitmap(imgpath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this work.
I've tried every answer I've found for this issue without success.
My users choose an image from their gallery to be displayed in an ImageView using Picasso, but it never get's loaded into the imageview.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == RESULT_OK){
if(requestCode == SELECT_PICTURE){
String selectedImageURI = data.getData().getPath();
File imageData = new File(String.valueOf(selectedImageURI));
//selectedImagePath = getPath(selectedImageURI);
if(!image1_exists){
Picasso.with(MemoriesActivity.this).load(imageData).noPlaceholder().centerCrop().fit().into(image1);
}
else if(!image2_exists){
//This is executed
Picasso.with(MemoriesActivity.this).load(imageData).noPlaceholder().centerCrop().fit().into(image2);
}
else if(!image3_exists){
//Picasso.with(MemoriesActivity.this).load(imageData).centerCrop().fit().into(image3);
}
}
}
}
public void addPhoto(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
I can't find any explainable cause for this except something must be wrong with onActivityResult together with Picasso, because I load images using exactly the same Picasso build/method when fetching images from my backend.
EDIT SOLUTION
public void attachImage(Uri uri, int imageIndex) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
InputStream stream;
try {
stream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(stream);
Bitmap image_scaled = Bitmap.createScaledBitmap(bitmap, 800, 800 * bitmap.getHeight() / bitmap.getWidth(), false);
if (imageIndex == 0) {
uploadImage(image_scaled, "image1");
handler.get(imageIndex).loadImageFromUri(this,(ImageView) findViewById(R.id.image1),uri);
handler.get(imageIndex).loadEnlargedImageFromUri(this,image1_full,uri);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
So I created that method (it's under construction, but the solution remains the same) and calls it like this in onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImage = data.getData();
int imageIndex = getFirstNonExistingImage();
if (imageIndex == 0) {
attachImage(selectedImage,imageIndex);
}
}
}
}
I load the URI with a custom Picasso class (handler.loadImageFromUri), but same principle.
Solved by creating an external method and executing that inside onActivityResult instead. No idea why, but it worked.
get real path from URI and set it to Picasso.
Uri selectedImage = data.getData();
imagePath = getRealPathFromURI(this, selectedImage);
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
You dont need to make cursor query with picasso.
With picasso you just need to write one line of code I have extended it for better understanding :-
//Get image Uri
Uri selectedImageURI = data.getData();
//Load image from picked Uri
Picasso.with(MainActivity1.this).load(selectedImageURI).noPlaceholder().centerCrop().fit()
.into((ImageView) findViewById(R.id.imageView1));
someone can tell me what the problem, it is not working, so please help fast i really need:
imagePick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"),1);
}
});
public void onActivityResult(int reqCode, int resCode, Intent data)
{
if(resCode==RESULT_OK)
{
if(reqCode==1) {
imageURI=data.getData();
iv.setImageURI(data.getData());
}
}
}
This is working for me.
private final static int SELECT_PHOTO = 12345;
imagePick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
imageView.setImageBitmap(bitmap);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
I am trying to give the user the option to either choose an image from the phone's storage or take one with the phone's camera app and then display that image in an imageView. With the help of this and this question I am able to display the image when it is choosen from the storage. However if I choose to take a picture with camera although I don't get an error the image is not shown in the imageView.
The function for choosing the picture looks like:
public void choosePic(View view) {
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[] { takePhotoIntent }
);
startActivityForResult(chooserIntent, SELECT_PICTURE);
}
After that it is handled by
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an image.
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
image = (ImageView) findViewById(R.id.imageView);
image.setImageURI(_uri);
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
}
EDIT
With #Murtaza Hussain's helps I was able to find a working solution:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("requestCode",""+requestCode);
if(requestCode == PICK_IMAGE && resultCode==RESULT_OK && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an image.
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
image = (ImageView) findViewById(R.id.imageView);
image.setImageURI(_uri);
cursor.close();
}
else if(requestCode== PICK_IMAGE && resultCode==RESULT_OK && data.getData() == null){
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
image =(ImageView) findViewById(R.id.imageView);
image.setImageBitmap(thePic);
}
super.onActivityResult(requestCode, resultCode, data);
}
You need to add code for it in onActivityResult()
if(requestCode==0 && resultCode==RESULT_OK ){
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
image =(ImageView) findViewById(R.id.imageView);
image.setImageBitmap(thePic);
}
In your activity when to capture image from camera. write the below code.
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"/imageLarge"+System.currentTimeMillis()+".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
In onActivityResult() write the below code..
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 111:
if(resultCode == RESULT_OK)
{
Log.v("","After camera capture path is --> "+mImageCaptureUri.toString().substring(8));
Bitmap bitmap=BitmapFactory.decodeFile(mImageCaptureUri.toString().substring(8));
image.setImageBitmap(bitmap);
}
else
{
}
}
}
Do not forget to add one permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In case of any query, Please let me know. Thanks.
I'm using an intent like this:
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
And in onActivityResult() I have this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return; // user cancelled
}
Uri imageUri = data.getData();
if (imageUri == null) {
// (code to show error message goes here)
return;
}
// Get image path from media store
String[] filePathColumn = { android.provider.MediaStore.MediaColumns.DATA };
Cursor cursor = this.getContentResolver().query(imageUri, filePathColumn,
null, null, null);
if (cursor == null || !cursor.moveToFirst()) {
// (code to show error message goes here)
return;
}
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
cursor.close();
if (imagePath == null) {
// error happens here
}
}
When I select images from particular albums like "Posts", "Profile Photos" (see screenshot) I'm unable to get the image path in onActivityResult(). Images from other albums can be selected with no problems.
I've tried adding intent.putExtra("return-data", true) but data.getExtras() returns null in onActivityResult().
There is similar question here, but no one answered it.
Please help!
hops this will helps you ....
ACTIVITYRESULT_CHOOSEPICTURE is the int you use when calling startActivity(intent, requestCode);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == ACTIVITYRESULT_CHOOSEPICTURE) {
BitmapFactory.Options options = new BitmapFactory.Options();
final InputStream ist = ontext.getContentResolver().openInputStream(intent.getData());
final Bitmap bitmap = BitmapFactory.decodeStream(ist, null, options);
ist.close();
}
}
if above code doesn't work than just refer this link... it will surly shows the way
http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/
try this:
String selectedImagePath = imageUri.getEncodedPath();
it works for me using gallery image picker
maybe this:
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());