Retrieving a photo from photo gallery - android

I have found this code and trying to implement in my application, it open the gallery, let's me select a photo, then the applications stops working and closes.
It's my first time trying to upload an image to mysql, and i'm stuck at the very beginning.
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showFileChooser();
}
});
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#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
{
bitmap = MediaStore.Images.Media.getBitmap(MainActivity.this.getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(bitmap);
}
}

Uri filePath = data.getData();
This will be meaningless for most Uri values.
The best solution to populate an ImageView from a Uri is by using a third-party image loading library, such as Picasso.
If you insist upon doing this yourself, you will need to fork a background thread, use a ContentResolver and openInputStream() to get an InputStream on the content backed by the Uri, use BitmapFactory and decodeStream() to get a Bitmap, then (on the main application thread) update the ImageView with the Bitmap.

Related

I pick Image from gallery to set background to widget but error

This is error when I pick a picture from gallery. I test on genymotion virtual.
java.lang.OutOfMemoryError: Failed to allocate a 83886092 byte allocation with 15855104 free bytes and 73MB until OOM
ImageView (activity_quotes.xml)
<ImageView
android:id="#+id/imgBG"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/defaultwall"/>
Button to pick image (MainActivity activity_main)
private void initChange()
{
btnChangeWall = (Button) findViewById(R.id.btnWall);
btnChangeWall.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 Your Picture"), PICK_IMAGE_REQUEST);
}
});
}
#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 uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
ImageView imageView = (ImageView) findViewById(R.id.imgBG);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: ImageView is not on MainActivity activity_main, it's on diffenrent class and activity (a Widget). You can see a pic2
This widget
QuotesWidget (inc activity_widget)

when i choose photo from gallery or take a picture from camera my photo is rotating?

im choosing a photo from gallery or taking a picture from camera and when it sets to an ImageView it's getting rotate , how can i fix it to become without rotate ?
public void setNewImage() {
new android.app.AlertDialog.Builder(getActivity())
.setPositiveButton("camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(takePicture, 0);
}
})
.setNegativeButton("gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
getActivity().startActivityForResult(pickPhoto, 1);
}
})
.show();
}
and here im setting the image to imageview :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
NewpostFragment.post_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
/* Uri picUri = data.getData();
filePath = getPath(picUri);
img.setImageURI(picUri);*/
}
break;
case 1:
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
/*Uri picUri = data.getData();
filePath = getPath(picUri);
img.setImageURI(picUri);*/
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
NewpostFragment.post_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
First, ACTION_IMAGE_CAPTURE will not give you a Uri via getData() in onActivityResult(). While some buggy camera apps may do that, most will not. Your choices are:
Provide EXTRA_OUTPUT on the ACTION_IMAGE_CAPTURE Intent, in which case the photo should be stored in the location identified by the Uri that you put into EXTRA_OUTPUT, or
Do not provide EXTRA_OUTPUT, and use getParcelableExtra("data") to get a thumbnail from the camera app
See this sample app for using ACTION_IMAGE_CAPTURE with EXTRA_OUTPUT.
In terms of orientation, if you go down the EXTRA_OUTPUT path, you can use android.support.media.ExifInterface to find out the orientation of the photo, then do something to rotate the image to match (e.g., rotate the ImageView).
See this sample app for using ExifInterface (though I am using a different implementation than android.support.media.ExifInterface).

Get Image from the Gallery and Show in ImageView

I need to get an image from the gallery on a button click and show it into the imageview.
I am doing it in the following way:
btn_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getImageFromAlbum();
}
});
The method Definition is as:
private void getImageFromAlbum(){
try{
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}catch(Exception exp){
Log.i("Error",exp.toString());
}
}
The activity result method is
#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) {
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();
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image_view.setImageBitmap(bmp);
//to know about the selected image width and height
Toast.makeText(MainActivity.this, image_view.getDrawable().getIntrinsicWidth()+" & "+image_view.getDrawable().getIntrinsicHeight(), Toast.LENGTH_SHORT).show();
}
}
The Problem
The problem I am facing is when the image resolution is high suppose that if the image size is of 5mp to 13mp. It won't loads up and show up into the image view.
But the images with the low width and height are successfully loading into the image view!
Can somebody tell me any issues with the code and what I am doing wrong? I just want to import the camera images from the gallery and show them in the image view!
you can try this.
paste this code in your button click event.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
and below code is your on activity result
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image_view.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
I hope it is helpful for you.
I use this code:
This code used to start gallery activity.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
And get the result in:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK)
switch (requestCode){
case GALLERY_REQUEST:
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
carImage.setImageBitmap(bitmap);
} catch (IOException e) {
Log.i("TAG", "Some exception " + e);
}
break;
}
}
And don't forget to declare permission in AndroidManifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Because OnActivityResult method is deprecated, proper way nowadays with AndroidX Activity, is Activity Result APIs, and that recommended way, see docs
"registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you’ll use to launch the other activity."
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
previewImage.setImageURI(uri);
}
});
And simply call
mGetContent.launch("image/*");
when needed.
startActivityForResult() is deprecated. Android introduced Activity Result Api for same purpose.
This is how to implement Activity Result
ActivityResultLauncher<Intent> imagePickerActivityResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result != null) {
Uri imageUri = result.getData().getData();
Glide.with(this)
.load(imageUri)
.into(R.id.profileImageView);
}
}
}
);
Call above code by calling launch() with intent
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
imagePickerActivityResult.launch(galleryIntent);
I try all the solutions above but they don't work for me . I saw a code from tutorialspoint website and it works for me very well this is the code :
final int PICK_IMAGE = 100;
Button button = findViewById(R.id.button33);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
});
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri imageUri;
ImageView imageView = findViewById(R.id.image_main_galary);
if (resultCode == RESULT_OK && reqCode == 100){
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
the most important issue : don't forget PERMISSION :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Android - Cannot set gallery image to ImageView

I've looked through tons of posts and cannot figure out why I can't get this to work. All I want to do is have the user click a button that opens up the gallery app. Then the user selects a picture which automatically closes out the gallery and goes back to my application where it automatically sets that image to an ImageView.
So far, I have it working all the way up until it goes back to my application. It seems to all be fine but the image never shows up in the ImageView.
Here is the XML code for the ImageView:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal" />
At the beginning of my activity I set the ImageView with this:
ImageView targetImage;
And here is the rest of my code to get the image and set it to my ImageView. There is a button that launches "setGunImage".
public void setGunImage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
targetImage = (ImageView)findViewById(R.id.imageView1);
Uri selectedImageUri = data.getData();
targetImage.setImageURI(selectedImageUri);
}
}
}
I have tested it on both the simulator with the sd card enabled and an image loaded into and also on a real device. Both give the same behavior. It goes through the gallery steps fine but when it goes back to my application there is no image loaded in the ImageView.
I tried changing the data to a bitmap and setting that but it never showed up either. I know it's probably something super simple that I'm just not seeing so hopefully a fresh pair of eyes can point me in the right direction. Thanks.
I think Imran solution should work fine .............. and you can also try this way
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if( resultCode==RESULT_OK)
{
if(requestCode==SELECT_PICTURE)
{
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
targetImage = (ImageView)findViewById(R.id.imageView1);
targetImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
from link
you are passing URI in setImageURI so fist get path of image using MediaStore.Images.Media.DATA and URI then pass path of image in setImageURI.
try this way:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( resultCode==RESULT_OK)
{
if(requestCode==SELECT_PICTURE)
{
targetImage = (ImageView)findViewById(R.id.imageView1);
Uri selectedImageUri = data.getData();
String selectedImagePath=getPath(selectedImageUri);
targetImage.setImageURI(selectedImageUri);
}
}
}
private String getPath(Uri uri)
{
String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(uri,projection,null,null,null);
int column_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Intercepting onActivityResult() for Camera application on Android

In my application, I'm trying to make it so the User can press a button, which will allow them to take a picture using the stock camera application on their phone.
I am following the guide to using an external Camera app to capture images that I can use in my own app from the Android Developers Guide (http://developer.android.com/guide/topics/media/camera.html#intent-receive)
I'm having trouble with the onActivityResult() method, it apparently takes in 3 parameters
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
Log.w("borre","Image saved to:\n" + data.getData());
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
But at the moment, the data Intent is coming back as null, so calling any methods on the Intent parameter throws a NullPointerException
Here's the code I'm using to call up the Camera application (It's basically the same as the code in the guide)
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Has anyone had this problem or knows why this Intent is coming back as null?
your are getting data part null bez you are not setting intent.setDataAndType() when you are starting Acitivty.like
public static final String IMAGE_UNSPECIFIED = "image/*";
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
startActivityForResult(intent, 3);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 0)
return;
if (requestCode == 2) {
Uri uri=data.getData(); //YOU GET DATA HERE
}
//OR
if (requestCode == 3) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)????
imageView.setImageBitmap(photo);
}
}
or in your case getting image path use:
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
//pic path
File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
}

Categories

Resources