I'm trying to add Pick image with Crop feature by aspect 1:4, it's 2000 width, 500 height => 1:4, and i want the selected image by user to replace an image located in drawable/custom_image.jpg.
Note : the image "custom_image" isn't showed as imageview in the app.
I've searched Stackoverflow, and found the ways, but i'm having a problem with cropping it & replacing that selected image with "R.drawable.custom_image".
EDIT : Forgot the cropping, got problems in it, i just need the replace drawable code in OnActivityResult.
I've created a button, when pressed it calls a method, here's the code :
Button mSelectbutton = (Button) view.findViewById(R.id.selectimage);
mSelectbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SelectImageActivity(v);
}
});
SelectImageActivity :
public void SelectImageActivity(View v) {
Intent selectintent = new Intent();
// Show only images, no videos or anything else
selectintent.setType("image/*");
selectintent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(selectintent, "Select Picture"), PICK_IMAGE_REQUEST);
}
And here's the method :
OnActivityResult Code :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && 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();
Drawable imageView = (Drawable)findViewById(R.drawable.custom_header);
imageView.setImageDrawable(getDrawable(R.drawable.custom_header);
}
}
I have used this library to tackle this problem because keeping outputx etc.. is not working for some versions of android:
Add this library to gradle:
//image cropping library to show as square for android older versions to work
compile 'com.soundcloud.android:android-crop:1.0.1#aar'
this method performs cropping:
private void performCrop(Uri mImageCaptureUri) {
//this creates a new image file comment below if you want file creation code
Uri destinationUri = MediaUtils.getOutputMediaFileUri(GlobalConstants.CREATE_IMAGE);
Crop.of(mImageCaptureUri,destinationUri).asSquare().start(getActivity(),this);
}
In your on activity result you can get Cropped image catch it:
if(requestCode == Crop.REQUEST_CROP) {
Uri outPutImageUri = Crop.getOutput(data);
Comment below if you want any futher info
Related
I'm building an android application which allow user to pick Image from camera or From Gallery then display the image in a Imageview.My application working fine if the user take the picture from camera, but if the user pick the image from gallery my application only work on android 9 and bellow,BitmapFactory.decodeFile(ImageFilePath) always return null on android 10 with the imageFilePath = "/storage/emulated/0/DCIM/Camera/20200629_114552.jpg"(path is the same on android 9 and 10). I've requested for read external storage permission before open gallery and then get the image path from onActivityResult like bellow:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case GALLERY_REQUEST_CODE:
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
if (!mNextImg) {
mBiomatrics_left_identity_img
.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
} else {
mBiomatrics_right_identity_img
.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
}
mNextImg = !mNextImg;
if (mBiomatrics_left_identity_img.getDrawable() != null
&& mBiomatrics_right_identity_img.getDrawable() != null) {
mBiomatrics_btn_confirm.setTextColor(getResources()
.getColor(R.color.mainTextColor));
} else {
mBiomatrics_btn_confirm.setTextColor(getResources()
.getColor(R.color.biometrics_btn_confirm_deactive_color));
}
break;
}
}
}
InputStream is = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(is);
Use this for all Android versions.
Stop with trying to get a path for an uri.
Solution: for Android 10,
All you need is this line: (in manifests)
android:requestLegacyExternalStorage="true"
I am dealing with Pick gallery images and show them in app also save their Path for some references in future.
I was able to Pick those images from gallery which are stored on device like in some folder like Downloads by this code:
Intent intent = new Intent (Intent.ActionPick, Android.Provider.MediaStore.Images.Media.ExternalContentUri);
intent.SetType ("image/*");
StartActivityForResult (Intent.CreateChooser (intent, "Select photo"), 0);
and in Result:
public override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult (requestCode, resultCode, data);
case 0:
string FilePath = GetPathToImage (data.Data);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string path = null;
string[] projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (ICursor cursor = this.Activity.ManagedQuery(uri, projection, null, null, null))
{
if (cursor != null)
{
int columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
else
{
return uri.Path;
}
}
}
My question is : I am able to get paths of images those are placed in some local folder in gallery, but for folders like Picasa/Autobackup I am not able to get Path.
Note:For local images path starts from content://
For Other com.android....like that.
So, Is there any workaround to get paths of those images.
I don't want to do like this to just display image:
final InputStream is = getContentResolver().openInputStream(imageUri);
I need a Path.
If there is no solution, then How can we skip those images being displayed while Picking from Gallery/Photos.
PS: Known Issue
Any Suggestion is appreciated.
Thanks
i made an application that will allow the user to take a camera shot and edit it using my application. I own a samsung galaxy stellar and it works fine on it. I had my friend download the application and when she tested it on her phone, my application crashes whenever she takes a picture and hit "save". shes using a galaxy s3.
Heres my code when im taking a picture
case R.id.ibTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+File.sep arator + fileName2 + ".jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
rotatePic = true;
startActivityForResult(i,cameraData);
break;
and heres my result code..
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
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 };
pictake = true;
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
rotatePic = false;
bmpReceive = rotate(picturePath);
bmpOriginal = bmpReceive;
picTaken.setImageBitmap(bmpReceive);
// ImageView imageView = (ImageView) findViewById(R.id.imgView);
// imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
I had a similar problem so I switched to this:
Uri uri= data.getData();
InputStream in = context.getContentResolver().openInputStream(uri);
Bitmap b = BitmapFactory.decodeStream(in);
hope it helps
Well, Logs help. But here is my guess.
If you check the Documentation.
http://developer.android.com/reference/android/content/ContentResolver.html
A query can return a Cursor object or null.
In your code you are not checking for the null. I suggest you try with that. In any case you should always put null checks wherever there is a chance for a null to be returned.
If you can provide the logs then we can tell you the exact problem.
Maybe the bitmap is too big and you get an out of memory. Check that page to know how to deal with that situation:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
I want a functionality in my app in which the user could select a background(.png/.jpg file) from the phone's memory. I guess 80% of my task has been completed by using this link http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/
The code from the above link just shows the view of SD card and now I want to set any image file present there as my app background. How can i achieve this?
If you want just select image and set background, I think the simpliest way is something like this:
.....
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PICTURE_ACTIVITY_REQUEST_CODE);
....
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PICTURE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
setBackgroundDrawable(new BitmapDrawable(bitmap));
}
cursor.close();
}
break;
}
}
Depending on your app, a FrameLayout around every existing layout, begun with an ImageView that you set appropriately.
If you want to do it dynamically use
setBackgroundColor(int color)
or
setBackgroundResource(int resourceID)
on your parentview of your activity.
Yuo can try this:
Bitmap srcBitmap = BitmapFactory.decodeStream(new FileInputStream(new File("path/to/file.jpg")));
BitmapDrawable bmpDrawable = new BitmapDrawable(srcBitmap);
YourView.setBackgroundDrawable(bmpDrawable);
I suppose your problem is that you don't know how to load image picked from a gallery. #appserv's answer solves your problem, but if you need to load images from any source (including your app resources), look at how it is implemented in ImageView
WHAT I HAVE DONE NOW:
i am picking images on my app with android, and showing them on a ImageView of my layout, and sometimes i got an exception java.lang.OutOfMemoryError: bitmap size exceeds VM budget. This happens when the photos are higher than 500kb.
WHAT I NEED TO DO (AND I DONT KNOW HOW TO DO IT):
then, what i want to do is to allow the user only to select photos of maximum 500kb. And if the user selects a photo Higher than 500kb, then, my app should show a toast telling the user that only can select photos of max 500kb.... ¿how to do it?
this is my code:
changeImageButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 1:
{
setResult(1);
finish();
}
case ACTIVITY_SELECT_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();
selectedPhoto = BitmapFactory.decodeFile(filePath);
//profileImage.setImageBitmap(selectedPhoto);
profileImage.setImageBitmap(Bitmap.createScaledBitmap(selectedPhoto, 80, 80, false));
}
}
}
profileImage is a ImageView of my layout. and i use scaled butmap to resice the image to 80x80
please give me some help to do that, im searching on google and i can't find nothing
Can't you just use some standard Java to get the file size, then check against your limit?
private long getFileSize(String path) {
File file = new File(path);
if (file.exists() && file.isFile()) {
return file.length();
} else {
return 0L;
}
}
Why do you hate your users so much? You are asking the wrong question... you don't need to cap the file size at all. It's the decompressed image size that's the problem, and you can control that.
Use the version of BitmapFactory.decodeFile() which takes a BitmapFactory.Options parameter, and then set the inSampleSize field of the options parameter to an appropriate value (2 or 4 or something). You may even want to use inJustDecodeBounds first to work out a reasonable value.