Android Intent ImageChooser Image Path - android

I am using Android Intent Chooser to select a photo from gallery with following code.
ivAvatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Bir fotoğraf seçin ..."), 1);
}
});
After selection using the path I fill the imageview with following code :
Uri selectedImageUri = data.getData();
imagepath = ImagePathUtil.getPath(getApplicationContext(), selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
ivAvatar.setImageBitmap(bitmap);
selectedU = selectedImageUri;
File f = new File(String.valueOf(selectedU));
if(f.exists())
{
int i = 1;
}
Image can be viewed without any problems, but the File object I create afterwards File 's exists() method always return false.

It is returning false because the file will be null. Please look at the below post for more details on how to get the real path from URI.
URI from Intent.ACTION_GET_CONTENT into File

Related

How to share image of app

I have picture in drawable and I want to share that one image.
Following is my code,
btnic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.defaultpicture);
Intent ppp = new Intent("android.intent.action.SEND");
ppp.setType("image/png");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
b, "defaultpicture", null);
Uri uri = Uri.parse(path);
ppp.putExtras(Intent.EXTRA_STREAM, uri); **i am getting error here**
MainActivity.this.startActivity(Intent.createChooser(ppp, "Send picture"));
Toast.makeText(getApplicationContext(), "Picture Copied", Toast.LENGTH_SHORT).show();
}
});
where am i doing wrong?
Intent.EXTRA_STREAM takes value as Local path of file on storage not on resource (Not a resource ID).
So you need to first save the image as file in storage then pass the url to sharing Intent .
First decode resource.
Bitmap b = BitmapFactory.decodeResource(res, id);
Save it to specific location on storage and use this file path as value in intent. you can save it as below or in some other way.
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
b, "myFile", null);
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpg");
final File photoFile = new File(getFilesDir(), "yourimage.jpg");
Log.d("TAG", "onClick: "+photoFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
startActivity(Intent.createChooser(shareIntent, "Share image using"));
for more about Sharing Content with Intents

Android : Share drawable resource with other apps

In my activity I have an ImageView. I want ,when user click on it, a dialog opens (like intent dialogs) that show list of apps which can open image than user can choose a app and show the image with that app.
my activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView iv = (ImageView) findViewById(R.id.imageid);
iv.setImageResource(R.drawable.dish);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here is where I want a dialog that I mentioned show
}
});
}// end onCreate()
You can't pass a bitmap to an intent.
From what I see you want to share a drawable from your resources. So first you have to convert the drawable to a bitmap. And then You have to save the bitmap to the external memory as a file and then get a uri for that file using Uri.fromFile(new File(pathToTheSavedPicture)) and pass that uri to the intent like this.
shareDrawable(this, R.drawable.dish, "myfilename");
public void shareDrawable(Context context,int resourceId,String fileName) {
try {
//convert drawable resource to bitmap
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
//save bitmap to app cache folder
File outputFile = new File(context.getCacheDir(), fileName + ".png");
FileOutputStream outPutStream = new FileOutputStream(outputFile);
bitmap.compress(CompressFormat.PNG, 100, outPutStream);
outPutStream.flush();
outPutStream.close();
outputFile.setReadable(true, false);
//share file
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/png");
context.startActivity(shareIntent);
}
catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG).show();
}
}
You have to startActivity using intent of type Intent.ACTION_VIEW-
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(<your_image_uri>, "image/*");
startActivity(intent);
Create a chooser by using the following code. You can add it in the part where you say imageview.setonclicklistener().
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

Allowing User to select Image from camera and Gallery dose not work for installed app like Camera360

I'm newbie in Android development. Well my application allows the user to select images from a gallery and to captures image taken from camera. Well it works perfectly fine while picking an image from a gallery and Native Camera but it dose not work when picking an image from an installed app like Camera360. Can anyone help me with this issue.
Below is my code to show a options to select images from Gallery and camera
File root = new File(Environment.getExternalStorageDirectory() + File.separator + "Test" + File.separator);
if (!root.exists())
root.mkdirs();
String fname = "img_" + System.currentTimeMillis() + ".jpg";
File sdImageMainDirectory = new File(root, fname);
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
List<Intent> cameraIntents = new ArrayList<Intent>();
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = getPackageManager();
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
String packageName = res.activityInfo.packageName;
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, PICK_IMAGE_REQUEST);
onActivityResult Method is implemeted below
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
Bitmap yourSelectedImage;
if (isCamera) {
yourSelectedImage = BitmapFactory.decodeFile(outputFileUri.getPath());
} else {
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 filePath = cursor.getString(columnIndex);
cursor.close();
yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
com.pkmmte.view.CircularImageView CircularImageView = (com.pkmmte.view.CircularImageView) findViewById(R.id.profileImage);
CircularImageView.setImageBitmap(yourSelectedImage);
}
}
}
The code works perfectly fine for both camera and gallery image picker. But it crashes for installed app like Camera360. Can some one help me regarding this
A Uri is not a file, and so you cannot pass it to decodeFile() on BitmapFactory. Your "pretend this Uri actually came from MediaStore" code will not work either.
Either use an image loading library like Picasso or Universal Image Loader, or have your own background thread that uses openInputStream() on a ContentResolver to read in the contents of that Uri, passing the stream to decodeStream() on BitmapFactory.
The code works perfectly fine for both camera and gallery image picker.
Only for the couple of cases that you tried. For example, if the "gallery image picker" returns an image that is on removable storage on Android 4.4+, even if you could get a filesystem path, you can't read it, as you don't have read access for arbitrary locations on removable storage.

View image in android built-in viewer

I need to view the image in android default image viewer when i execute the following code it's shows the album list instead Of particular image. please correct me.
MediaScannerConnection.scanFile(this, new String[] {receiptPath}, new String[] {"image/*"}, new MediaScannerConnection.OnScanCompletedListener()
{
#Override
public void onScanCompleted(String path, Uri uri)
{
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setType("image/*");
startActivity(intent);
}
});
I have found the answer for my question see the answer below
#Override
public void onScanCompleted(String path, Uri uri)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
after analyse the android Intent source code my learning is, if you set uri in Intent constructor then set type, the data uri automatically set to null, so i can't access the particular image in image viewer.
Refer the source

URI/URL Paths from Gallery and Camera-taken-photo are different

I am trying to get the users to select between taking a picture with the device default camera and select from the gallery of images also default to the device.
I can get the camera to take the picture and have it display within the app just fine since it seems to like the URI pathing straight to a JPG file. However, the pathing given to the gallery URI is very different and does not display the image at all.
Here are the pathes I get:
WHEN TAKEN FROM CAMERA:
/mnt/sdcard/filename.jpg
WHEN CHOSEN FROM GALLERY:
/external/images/media/# (# is the ID number/thumbnail I believe)
The code used for retrieving both pathes are:
CAMERA:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri =
Uri.fromFile(new file(Environment.getExternalStorageDirectory(),
"fname_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
GALLERY:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
With the Gallery, it opens and I can browse just fine, it just doesn't display the image as it does with taking the picture.
The code used for pulling the images into my app once selected/taken is:
ImageView getMyphoto = (ImageView) findViewById(R.id.usePhoto);
String stringUrl = prefSettings.getString("myPic", "");
Uri getIMG = Uri.parse(stringUrl);
getMyphoto.setImageURI(null);
getMyphoto.setImageURI(getIMG);
Check for the "/external" in the uri string and then use get the right path method to get the absolute path.
private String getRealPathFromURI(Uri contentUri) {
int columnIndex = 0;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
try {
columnIndex = cursor.getColumnIndexOrThrow
(MediaStore.Images.Media.DATA);
} catch (Exception e) {
Toast.makeText(ImageEditor.this, "Exception in getRealPathFromURI",
Toast.LENGTH_SHORT).show();
finish();
return null;
}
cursor.moveToFirst();
return cursor.getString(columnIndex);
}

Categories

Resources