Picasso not loading image from gallery - android

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));

Related

How to get address from gallery in android

I write this code and my code choose one picture from gallery and get data from it but I dont konw how to get image address from Inputstrem or data and store it?
public void loadPic()
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1)
{
try {
Uri selectedImage=data.getData();
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
listItems.add(inputStream.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Read filename name like below, use it accordingly.
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
File f = new File(picturePath);
String imageName = f.getName();
Sometimes, you can't get a file from the picture you choose.
It's because the choosen one came from Google+, Drive, Dropbox or any other provider.
The best solution is to ask the system to pick a content via Intent.ACTION_GET_CONTENT and get the result with a content provider.
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
I'm not sure if this is exactly what you want, but you can get the image like this:
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
Once you have the Bitmap, you can see here on how to store it.
EDIT: Try this
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Taken from here.

Android pick image from gallery not working (Android 6.0 & Android 5.1.1)

I'm using the code below to pick an image file from device gallery:
First I call this piece of code:
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select Picture"), RESULT_LOAD_IMAGE);
This is my onActivityResult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
photoPath = getPath(data.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(new File(photoPath));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf))) {
baos.write(buf, 0, n);
}
img.setImageBitmap(BitmapFactory.decodeFile(photoPath));
} catch (Exception e) {
e.printStackTrace();
}
}
}
And this a helper method to retrieve image path:
private String getPath(Uri uri) {
String[] data = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), uri, data, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
My problem is that the app is weird. In my 6.0 emulator, sometimes it works and sometimes No. In an other device (Android 5.1.1) an FileNotFound Exception is thrown at this line
fis = new FileInputStream(new File(photoPath));
All required permissions are fine.Do you guys have any idea what's going on here? Or do you have any better suggestion what to use to pick an image from gallery?
Try this you can directly set image from onActivityResult
#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) {
try{
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Step #1: Delete the ByteArrayOutputStream, as you are not using it.
Step #2: Delete photoPath = getPath(data.getData()); and the getPath() method, as they are wrong.
Step #3: Use an image loading library to asynchronously populate your ImageView, passing it the Uri (data.getData()) of the image to load. Or, roll lots of your own image-loading code, including forking a background thread and using getContentResolver().openInputStream() to get an InputStream on the content identified by the Uri.
you can use like below code
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
//you are in fragment so use the below code hope its work
final Uri imageUri = data.getData();
final InputStream imageStream =getActivity().getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

Android - Choose Image from Gallery and store it in a File type variable

I am a new to Android Development. I wish to select an image or a video from the Gallery of an Android Device. Store it in a variable of typeFile. I am doing this, since I need to upload the image/video on dropbox using the Android API from my application. The constructor takes in the fourth parameter of the type File. I am not sure, what to pass as a file since all the examples I searched display the image chosen in an ImageView by using the url and making a bitmap.
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Here is the code, I have.
final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
//to get image and videos, I used a */"
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, 1);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
yourSelectedImage = BitmapFactory.decodeFile(filePath);
return cursor.getString(column_index);
}
All you need to do is just create a File variable with the path of image which you've selected from gallery. Change your OnActivityResult as :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
File imageFile = new File(imagepath);
}
}
this works for image selection. also tested in API 29,30. if anyone needs it.
private static final int PICK_IMAGE = 5;
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "select image"),
PICK_IMAGE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
File imageFile = new File(selectedImagePath);
}
}
public String getRealPathFromURIForGallery(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(uri, projection, null,
null, null);
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
assert false;
cursor.close();
return uri.getPath();
}
Try this
You can try this also
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK && data != null)
{
File destination = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
//You will get file path of captured camera image
Bitmap photo = (Bitmap) data.getExtras().get("data");
iv_profile.setImageBitmap(photo);
}
}

To select image from galary from Application sometimes it returns bitmap - nulll in Android?

In Application i open gallery and select image i have to show that image in dialog box..
bu sometimes it returen bitmap value =null.. and somtimes it has bitmap value does not show dialog box.. it throughs exceptioni.e
java.lang.NullPointerException
04-16 10:11:52.310: WARN/System.err(1395): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:432)
04-16 10:11:52.310: WARN/System.err(1395): at myclassname.onActivityResult
for iopen gallery i used below code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) context).startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_FROM_FILE);
Foe getting data from gallery i used this code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK)
{
Uri selectedImage = data.getData();
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Plz help ..
In you onActivityResult change the code to receive the image to this code,
if (resultCode == RESULT_OK && requestCode == PICK_FROM_FILE) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String tmppath = cursor.getString(column_index); // get path of image
Bitmap mBitmap = BitmapFactory.decodeFile(tmppath); // decode path into bitmap
iv.setImageBitmap(mBitmap); // set image to imageview
}

How to pick an image from gallery (SD Card) for my app?

This question was originally asked for Android 1.6.
I am working on photos options in my app.
I have a button and an ImageView in my Activity. When I click the button it would redirect to the gallery and I would be able to select an image. The selected image would appear in my ImageView.
Updated answer, nearly 5 years later:
The code in the original answer no longer works reliably, as images from various sources sometimes return with a different content URI, i.e. content:// rather than file://. A better solution is to simply use context.getContentResolver().openInputStream(intent.getData()), as that will return an InputStream that you can handle as you choose.
For example, BitmapFactory.decodeStream() works perfectly in this situation, as you can also then use the Options and inSampleSize field to downsample large images and avoid memory problems.
However, things like Google Drive return URIs to images which have not actually been downloaded yet. Therefore you need to perform the getContentResolver() code on a background thread.
Original answer:
The other answers explained how to send the intent, but they didn't explain well how to handle the response. Here's some sample code on how to do that:
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
}
}
After this, you've got the selected image stored in "yourSelectedImage" to do whatever you want with. This code works by getting the location of the image in the ContentResolver database, but that on its own isn't enough. Each image has about 18 columns of information, ranging from its filepath to 'date last modified' to the GPS coordinates of where the photo was taken, though many of the fields aren't actually used.
To save time as you don't actually need the other fields, cursor search is done with a filter. The filter works by specifying the name of the column you want, MediaStore.Images.Media.DATA, which is the path, and then giving that string[] to the cursor query. The cursor query returns with the path, but you don't know which column it's in until you use the columnIndex code. That simply gets the number of the column based on its name, the same one used in the filtering process. Once you've got that, you're finally able to decode the image into a bitmap with the last line of code I gave.
private static final int SELECT_PHOTO = 100;
Start intent
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
Process result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
}
}
}
Alternatively, you can also downsample your image to avoid OutOfMemory errors.
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 140;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
You have to start the gallery intent for a result.
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
Then in onActivityForResult, call intent.getData() to get the Uri of the Image. Then you need to get the Image from the ContentProvider.
Here is a tested code for image and video.It will work for all APIs less than 19 and greater than 19 as well.
Image:
if (Build.VERSION.SDK_INT <= 19) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, 10);
} else if (Build.VERSION.SDK_INT > 19) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 10);
}
Video:
if (Build.VERSION.SDK_INT <= 19) {
Intent i = new Intent();
i.setType("video/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, 20);
} else if (Build.VERSION.SDK_INT > 19) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 20);
}
.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 10) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURI(selectedImageUri);
} else if (requestCode == 20) {
Uri selectedVideoUri = data.getData();
String selectedVideoPath = getRealPathFromURI(selectedVideoUri);
}
}
}
public String getRealPathFromURI(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
Do this to launch the gallery and allow the user to pick an image:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK);
Then in your onActivityResult() use the URI of the image that is returned to set the image on your ImageView.
public class EMView extends Activity {
ImageView img,img1;
int column_index;
Intent intent=null;
// Declare our Views, so we can access them later
String logo,imagePath,Logo;
Cursor cursor;
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;
String selectedImagePath;
//ADDED
String filemanagerstring;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img= (ImageView)findViewById(R.id.gimg1);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
//UPDATED
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
img.setImageURI(selectedImageUri);
imagePath.getBytes();
TextView txt = (TextView)findViewById(R.id.title);
txt.setText(imagePath.toString());
Bitmap bm = BitmapFactory.decodeFile(imagePath);
// img1.setImageBitmap(bm);
}
}
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
}
public class BrowsePictureActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
if( uri == null ) {
return null;
}
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
}
For some reasons, all of the answers in this thread, in onActivityResult() try to post-process the received Uri, like getting the real path of the image and then use BitmapFactory.decodeFile(path) to get the Bitmap.
This step is unnecessary. The ImageView class has a method called setImageURI(uri). Pass your uri to it and you should be done.
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
For a complete working example you could take a look here: http://androidbitmaps.blogspot.com/2015/04/loading-images-in-android-part-iii-pick.html
PS:
Getting the Bitmap in a separate variable would make sense in cases where the image to be loaded is too large to fit in memory, and a scale down operation is necessary to prevent OurOfMemoryError, like shown in the #siamii answer.
call chooseImage method like-
public void chooseImage(ImageView v)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(imageReturnedIntent != null)
{
Uri selectedImage = imageReturnedIntent.getData();
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK)
{
Bitmap datifoto = null;
temp.setImageBitmap(null);
Uri picUri = null;
picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
if(picUri !=null){
try {
datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
temp.setImageBitmap(datifoto);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (OutOfMemoryError e) {
Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
}
}
}
break;
}
}
else
{
//Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
}
}
#initialize in main activity
path = Environment.getExternalStorageDirectory()
+ "/images/make_machine_example.jpg"; #
ImageView image=(ImageView)findViewById(R.id.image);
//--------------------------------------------------||
public void FromCamera(View) {
Log.i("camera", "startCameraActivity()");
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 1);
}
public void FromCard() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 2);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
image.setImageBitmap(bitmap);
if (bitmap != null) {
ImageView rotate = (ImageView) findViewById(R.id.rotate);
}
} else {
Log.i("SonaSys", "resultCode: " + resultCode);
switch (resultCode) {
case 0:
Log.i("SonaSys", "User cancelled");
break;
case -1:
onPhotoTaken();
break;
}
}
}
protected void onPhotoTaken() {
// Log message
Log.i("SonaSys", "onPhotoTaken");
taken = true;
imgCapFlag = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(path, options);
image.setImageBitmap(bitmap);
}

Categories

Resources