Android - How to get the image using Intent data - android

I implemented the application for getting image from the camera album in sdcard.But it is not working properly.
Here Intent returns like this Intent { act=com.htc.HTCAlbum.action.ITEM_PICKER_FROM_COLLECTIONS dat=content://media/external/images/media/9 typ=image/jpeg (has extras) }
In the code
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
Here (Bitmap) data.getExtras().get("data")
this part returns null.
How to get the bitmap here please can anybody help me.
Code:
cam_images_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent cam_ImagesIntent = new Intent(Intent.ACTION_GET_CONTENT);
cam_ImagesIntent.setType("image/*");
startActivityForResult(cam_ImagesIntent, CAMERA_IMAGES_REQUEST);
}
});
if(requestCode == CAMERA_IMAGES_REQUEST && resultCode==Activity.RESULT_OK)
{
System.out.println("data(CAMERA_IMAGES_REQUEST):"+data);
if(data != null)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
System.out.println("Bitmap(CAMERA_IMAGES_REQUEST):"+thumbnail);
System.out.println("cap_image(CAMERA_IMAGES_REQUEST):"+cap_image);
cap_image.setImageBitmap(thumbnail);
}
else
{
System.out.println("SDCard have no images");
Toast.makeText(camera.this, "SDCard have no images", Toast.LENGTH_SHORT);
}
}
thanks

Do the following in your code:
if(data != null)
{
Uri selectedImageUri = data.getData();
filestring = selectedImageUri.getPath();
Bitmap thumbnail = BitmapFactory.decodeFile(filestring, options2);
System.out.println("Bitmap(CAMERA_IMAGES_REQUEST):"+thumbnail);
System.out.println("cap_image(CAMERA_IMAGES_REQUEST):"+cap_image);
cap_image.setImageBitmap(thumbnail);
}
This should work.
Edit:
Also if you want a "thumbnail" do the following:
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(), selectedImageUriId,
MediaStore.Images.Thumbnails.MICRO_KIND,
(BitmapFactory.Options) null);

Well the way go about doing this is very easy, just:
//Get incoming intent
Intent intent = getIntent();
intent.setType("image/*");
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
handleIncomingData(intent);
}
public void handleIncomingData(Intent data){
Uri imageSelected = data.getParcelableExtra(Intent.EXTRA_STREAM);
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageSelected);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Remember to put this code after everything is initialized first or else you will get a NullPointerException. I prefer to put it at the bottom of the onCreate()

This problem can be solved by writing fewer lines of codes.
if(requestCode== your_request_code){
if(resultCode==RESULT_OK){
Uri uri = data.getData(); //<----get the image uri
imageView.setImageURI(uri); //<----set the image uri
}

I have this code:
public void onGalleryRequest() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent,
getResources().getString(R.string.selectImage)),
GALLERY_REQ);
}
and then in onActivityResult I make this test:
if (requestCode == CAMERA_PIC_REQUEST && data != null
&& resultCode != 0)
it works for me api level 7

Related

how to add image in one fragment and display it in another fragment/pass image through bundle in android

i want to select image in one fragment and display it in another fragment.
how can i do this.
my code is this but not working
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, 100);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Uri imageUri;
if (resultCode == RESULT_OK && requestCode == 100){
imageUri = data.getData();
file1path = imageUri.getPath();
TVfrontimg.setText(file1path);
}
}
and i send this using bundle
Bundle bundle = new Bundle();
bundle.putString("image1", file1path);
registerPartThreeFragment.setArguments(bundle);
transaction.replace(R.id.FLcontainer, registerPartThreeFragment);
transaction.addToBackStack(null);
transaction.commit();
in another fragment
String imgPath = getArguments().getString("image1");
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(new File(imgPath)));
imageview.setImageBitmap(bitmap);
but its not working.please help.
its giving me this error
2020-05-30 00:16:20.808 8995-8995/com.example.deliveryapp E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /raw/storage/emulated/0/DCIM/Camera/IMG_20200319_173033.jpg (No such file or directory)
Please use getDataString() instead of getData()
if (resultCode == RESULT_OK && requestCode == 100){
Uri imageUri = Uri.parse(data.getDataString());
//imageUri = data.getData();
file1path = imageUri.getPath();
TVfrontimg.setText(file1path);
}
And while setting it to the ImageView use ContentResolver and input stream like so:
ContentResolver cR = getApplication().getContentResolver();
try {
InputStream ip = cR.openInputStream(imageUri);
Bitmap bmp = BitmapFactory.decodeStream(ip);
imageView.setImageBitmap(bmp)
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You have to do this because you are getting a contentUri which is different from a file Uri.
Hope this helps.
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
This code you are want showing for image
You should look find real path
Look at answers : Get filepath and filename of selected gallery image in Android
android get real path by Uri.getPath()
In your first fragment
if (resultCode == RESULT_OK && requestCode == 100){
val bundle = Bundle()
bundle.putString("Image",your_image_path)
findNavController().navigate(R.id.your_destination_fragment, bundle)
}
in second fragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
image= it.getString("Image")
bitmp= MediaStore.Images.Media.getBitmap(
requireActivity().contentResolver,
Uri.parse(image)
}
and set your bitmap in imageview
imgBitmap.setImageBitmap(bmp)

How to make a "ImageView" field as mandatory in android?

I have a imageview field in my android app, onclick of the same I have given a "open camera" functionality and the user can click the photo from camera and it gets uploaded to ImageView
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user_image.getDrawable() == null ){
Toast.makeText(NewCall4.this, "No image uploaded", Toast.LENGTH_SHORT).show();
}
else{
Intent i=new Intent(NewCall4.this,NewCall5.class);
startActivity(i);
}
}
}
);
What I want is, if I am not uploading the image in the imageview then it should give the error/toast message as "Image not uploaded"
You Can check the Drawable if attached to ImageView
Imageview imageView = (ImageView)findViewById(R.id.image);
if(imageView.getDrawable() == null){
//Then Nothing is attached with imageviw
}
It is so simple. When You call Intent for camera open it gives callback in onActivityResult in that just pass the value of the image. And check it is null or not in the click event.
Example :-
=> To Open Camera :-
Intent intent1 = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, camera);
You will get a callback in onActivityResult
=> onActivityResult :- ( I am getting actual Image path here)
if (resultCode == RESULT_OK && requestCode == camera) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
addprofile.setImageBitmap(photo); // set image to imageview
Uri tempUri = getImageUri(getApplicationContext(), photo);
File finalfile = new File(getrealpathfromuri(tempUri));
imagepath = finalfile.toString(); // imagepath is a global variable
}
private Uri getImageUri(Context applicationContext, Bitmap photo) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(),photo,"Title",null);
return Uri.parse(path);
}
private String getrealpathfromuri(Uri tempUri) {
String path = "";
if(getContentResolver() != null){
Cursor cursor = getContentResolver().query(tempUri, null, null, null, null);
if(cursor != null){
cursor.moveToFirst();
int idk = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idk);
cursor.close();
}
}
return path;
}
Finally imagepath has an actual path of the image.
=> Check imagepath null or not :- (in event)
if (imagepath == null) {
Toast.makeText(this, "Please Select FileImage", Toast.LENGTH_SHORT).show();
}
Hi you can try something like this
Imageview img = (ImageView)findViewById(R.id.image){
img .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, id);
}
});
And OnResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap photo = (Bitmap) data.getExtras().get(“data”);
img.setImageBitmap(photo);
}

After captured an image I cant display it on imageview unless i save it in bitmap form. I need save it in Uri form

In my app, when users clicking an imageview, users can choose an image from gallery or capture an image from camera and display it on imageview. I can display the image on imageview if the image is selected from gallery but it failed to display if the image is captured. The imageUri is null if the image is captured.
Can anyone help me to solve this problem?
There are some codes below, if you need more info please comment below
private final static int PICK_IMAGE_REQUEST = 1;
private final static int CAMERA = 2;
private Uri imageUri;
private void takePhotoFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
#Override
public 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) {
imageUri = data.getData();
Picasso.get().load(imageUri).into(circleImageView);
System.out.println("haha pic " + imageUri);
}
if (requestCode == CAMERA && resultCode == RESULT_OK && data != null && data.getData() != null){
imageUri = data.getData();
Picasso.get().load(imageUri).into(circleImageView);
System.out.println("haha camera " + imageUri);
}
}
I would suggest you display your image as a bitmap on imageview, after that convert it into url form and store into database.
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
call this method in your onActivityResult method and put this code inside
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
circleImageView.setImageBitmap(bitmap);
imageUri = getImageUri(getApplicationContext(),bitmap);

setImageBitmap not displaying

On click, my app gives choice between camera and gallery and that picture is then displayed in an ImageView. I originally tried to display the full image and then tried to use the bitmap way but nothing works. I just get a blank ImageView. Please give me some guidance as to what I'm doing wrong and ask for clarifications if necessary:
Camera/gallery photo code:
Uri outputFileUri;
private void openImageIntent() {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_" + System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final 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.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent returnIntent) {
super.onActivityResult(resultCode, requestCode, returnIntent);
if(requestCode == 0) {
if(resultCode == RESULT_OK) {
final boolean isCamera;
if(returnIntent == null) {
isCamera = true;
}
else
{
final String action = returnIntent.getAction();
if(action == null) {
isCamera = false;
}
else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if(isCamera) {
selectedImageUri = outputFileUri;
mainImage.setImageURI(selectedImageUri); //trying full image
}
else {
selectedImageUri = returnIntent == null ? null : returnIntent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
mainImage.setImageBitmap(bitmap); //trying bitmap
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
your code is 2000000000000000% ok i test it myself
Your problem is your ImageView can't show image because of image size. I try this code with ImageView like this
<ImageView
android:id="#+id/mainImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/abc_ab_bottom_solid_dark_holo" />
If you use height and width with dp like this
android:layout_width="100dp"
android:layout_height="100dp"
You need to compress the Bitmap to show it in ImageView.
Edit your code to conversion
if(isCamera) {
selectedImageUri = outputFileUri;
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);//You can use this bitmap if need full image to further use
Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, 600 ,600, true);//this bitmap2 you can use only for display
mainImage.setImageBitmap(bitmap2); //trying full image
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
selectedImageUri = returnIntent == null ? null : returnIntent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
bitmap = Bitmap.createScaledBitmap(bitmap, 600 ,600, true);
mainImage.setImageBitmap(bitmap); //trying bitmap
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to take image from camera you can go with this process:
public void fromCamera(){
String path= Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
File file = new File(path,"IMG_"+System.currentTimeMillis()+".jpg");
file.getParentFile().mkdirs();
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
mPicCaptureUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicCaptureUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
And if you want image from gallery then :
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_file)), REQUEST_GALLERY);
On your onActivityResult you can get the image path of selected one and set image in image view....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if (requestCode == REQUEST_GALLERY && data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
//do set your image here
}else if(requestCode == REQUEST_CAMERA){
if(mPicCaptureUri!=null){
//do try to set image here
}
}
}
}
don't forgrt to define mPicCaptureUri at the top as:
private Uri mPicCaptureUri = null;
You can take idea from above code ..it might help you
Now you could use Picasso Library :D
Picasso.with(context)
.load(item.getPhotoUri())
.resize(512,512)
.placeholder(R.drawable.noimage)
.error(R.drawable.error_image)
.into(photo);
This mostly happens due to image being too big to be rendered by bitmap within that span of nano second during runtime, so you won't see it. Use a library called Glide. It solved all my image issues in Android including performance when there are hundreds of images to be displayed in a single list or grid.

pass uri to another activity and convert it to image

How to send a uri path of an image to another activity and convert it to image. I tried the below
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
//file name
Uri selectedImage = data.getData();
Intent i = new Intent(this,
AddImage.class);
i.putExtra("imagePath", selectedImage);
startActivity(i);
and get it like this
String imagePath = getIntent().getStringExtra("imagePath");
imageview.setImageURI(Uri.parse(imagePath ));
Convert you URI to String while adding to Intent like given below
i.putExtra("imagePath", selectedImage.toString());
and in your NextActivity get the String and convert back to URI like ->
Intent intent = getIntent();
String image_path= intent.getStringExtra("imagePath");
Uri fileUri = Uri.parse(image_path)
imageview.setImageURI(fileUri)
First Activity
Uri uri = data.getData();
Intent intent=new Intent(Firstclass.class,secondclass.class);
intent.putExtra("imageUri", uri.toString());
startActivity(intent);
Second class
Imageview iv_photo=(ImageView)findViewById(R.id.iv_photo);
Bundle extras = getIntent().getExtras();
myUri = Uri.parse(extras.getString("imageUri"));
iv_photo.setImageURI(myUri);
to use the returned uir from the calling activity and then set it to a imageview you can do this
Uri imgUri=Uri.parse(imagePath);
imageView.setImageURI(null);
imageView.setImageURI(imgUri);
This is a workaround for refreshing an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.
For converting the inputStream into a bitmap you could do this
InputStream in = getContentResolver().openInputStream(Uri.parse(imagePath));
Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(in));
and then call
image.setImageBitmap(bm);
to set it it a imageview,
you could also check this link for an example
hope i could help
in Next activity get that URI like this;
Intent intent = getIntent();
String image_path= intent.getStringExtra("YOUR Image_URI");
and to convert that Image_URI to Image use Below mentioned Code
File imgFile = new File(image_path);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}
To pass an image Uri to the next activity, you can just use setData() and getData(). There is no need to convert the Uri to anything.
First Activity
Intent intent = new Intent(this, SecondActivity.class);
intent.setData(uri);
startActivity(intent);
Second Activity
// get Uri
Uri uri = getIntent().getData();
// decode bitmap from Uri
if (uri == null) return;
try {
InputStream stream = getContentResolver().openInputStream(uri);
if (stream == null) return;
Bitmap bitmap = BitmapFactory.decodeStream(stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources