i am using a library for picking images from gallery and it is working , the problem is when i set the bitmap to the imageview it creates alot of duplicates in the gallery
here is the code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 11 && resultCode == RESULT_OK && data != null) {
ArrayList<Image> images = (ArrayList<Image>) ImagePicker.getImages(data);
for (int i = 0; i < images.size(); i++) {
String s = images.get(i).getPath();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
try {
bitmap = BitmapFactory.decodeFile(s, bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
imagesUrl2.add(bitmap);
uploadImages();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
the problem was with the glide loading from local uri ,it creates alot of instances in the gallery to get the image , so i passed the original uri of the images
Related
I'm trying to create simple Contact app. Naturally there is Contact class with member variable mCurrentPhotoPath. An activity which is responsible for creating Contact, has an option to pick image from Gallery in the following way:
final Intent pickImage = new Intent(Intent.ACTION_GET_CONTENT);
pickImage.setType("image/*")
/*some code...*/
galleryButton.setOnClickListener((View v) -> {
startActivityForResult(pickImage, REQUEST_GALLERY_PHOTO);
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK){
photoTaken = true;
Uri selectedImage = data.getData();
Log.i("path", selectedImage.getPath()) //prints out: /document/image:292562
mPhotoView.setImageURI(selectedImage);
I am able to display selected image in ImageView (mPhotoView).
However, when I try to set Intent in different way, I get full path, but I cannot recreate file from that path and I get FileNotFoundException.
final Intent pickImage = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK){
photoTaken = true;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Log.i.("TAG", picturePath); //I get, /storage/emulated/0/Pictures/Viber/IMG-bbd54c96cc971a1700f92205937014c8-V.jpg
mPhotoFile = new File(picturePath);
cursor.close();
updatePhotoView(); //This method recreates image based on exact file path and witdh & height of ImageView where the picture is going to be placed;
}
}
}
Here is updatePhotoView()
private void updatePhotoView(int imageWidth, int imageHeight) {
if (mPhotoFile == null || !mPhotoFile.exists()) {
mPhotoView.setImageDrawable(null);
} else {
Bitmap bitmap = PictureUtils.getScaledBitmap(mPhotoFile.getPath(),imageWidth, imageHeight); // imageWidth & imageHeight are member variables of actiivty...
mPhotoView.setImageBitmap(bitmap);
}
}
I'm pretty sure this function works, because when I implemented option to take picture from camera (I created file with getExternalFilesDir(), and in any other activity when I passed string value of mCurrentPhotoPath, getScaledBitmap() managed to recreate image).
Here is getScaledBitmap():
public static Bitmap getScaledBitmap(String path, int destWidth, int destHeight) {
// Read in the dimensions of the image on disk
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
// Figure out how much to scale down by
int inSampleSize = 1;
if (srcHeight > destHeight || srcWidth > destWidth) {
if (srcWidth > srcHeight) {
inSampleSize = Math.round(srcHeight / destHeight);
} else {
inSampleSize = Math.round(srcWidth / destWidth);
}
}
options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
// Read in and create final bitmap
return BitmapFactory.decodeFile(path, options);
}
Just if anyone stumbles on similar problem. I solved my problem of getting images by using Glide library. Look it up, bunch of tutorials. I guess that this load function is doing heavy lifting in the background. Great thing! Here is how code looks like:
Glide.with(context)
.load(imageFilePath)
.apply(new RequestOptions().centerCrop())
.override(imageView.getWidth(), imageView.getHeight())
.into(imageView);
I am trying to choose an image for registration. When clicking the ImageView, the user will be given a choice between taking a picture or choosing from his/her gallery. When the user chooses the gallery option, it will display the selected image. When the user chooses the camera option, the ImageView does not display the image. Below is my code for the OnActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent imgdata) {
super.onActivityResult(requestCode, resultCode, imgdata);
if (requestCode == SELECT_IMAGE && resultCode == RESULT_OK && imgdata != null) {
selectedimage = imgdata.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(selectedimage);
Bitmap yourselectedimage = BitmapFactory.decodeStream(inputStream);
imgchild.setImageBitmap(yourselectedimage);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
}
if (requestCode == CAPTURE_IMAGE && resultCode == RESULT_OK && imgdata != null) {
camImg =(Bitmap) imgdata.getExtras().get("img");
try {
imgchild.setImageBitmap(camImg);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
}
}
The ImageView should display the taken picture from the camera.
I think it should be like this
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
By reading your code, I think it's highly likely that camImg is null because the way you extract bitmap from Intent is incorrect.
Bitmap implements Parcelable, so you need to extract it like this:
camImg = (Bitmap) imgdata.getParcelableExtra("img");
I hope this will work for you.
Set image like this
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Uri tempUri = getImageUri(getApplicationContext(), photo);
File finalFile = new File(getRealPathFromURI(tempUri));
Log.e("path", finalFile.getAbsolutePath());
To get image path where it is stored
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
I faced same issue with Android Marshmallow, in my case, it is happening due to large bitmap so I figured out with the following code by resizing bitmap
final int maxSize = 960;
int outWidth;
int outHeight;
int inWidth = CameraActivity.bitmap.getWidth();
int inHeight = CameraActivity.bitmap.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
iv_captured_image.setImageBitmap(Bitmap.createScaledBitmap(CameraActivity.bitmap, outWidth, outHeight, false));
everybody
I have a trouble with my code and i dont know what is wrong.
I just want to take a photo with the native camera and display it in a ImageView.
Here's my code
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_IMAGE_CAPTURE);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap m = null;
try {
m = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
imgActa1.setImageBitmap(m);
}
On a Galaxy Tab everything works fine. In my Galaxy S4 the imageview keep null, and on a Alcatel OneTouch the app throws me an exception.
What can i do with this?
Thanks.
Use this code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
hope this helps you
Things have changed ver higher sdk version ,
you can use this code to get imgae
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == RESULT_LOAD_IMAGE) {
Uri selectedImageUri = data.getData();
if (Build.VERSION.SDK_INT < 19) {
String selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = decodeSampledBitmapFromPath(selectedImagePath,150,150);
icon.setImageBitmap(bitmap);
}
else {
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = decodeSampledBitmapFromFd(fileDescriptor, 150, 150);
parcelFileDescriptor.close();
icon.setImageBitmap(image);
prefEditor.putString(Constants.IMAGETEXT, ConvertImageToBase64.convertResource(image));
prefEditor.commit();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static Bitmap decodeSampledBitmapFromFd(FileDescriptor fileDescriptor,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, new Rect(-1, -1, -1, -1) , options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fileDescriptor, new Rect(-1, -1, -1, -1), options);
}
public static Bitmap decodeSampledBitmapFromPath(String path,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile( path,options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
///*
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK && null != data){
uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(prjection[0]);
ImagePath = cursor.getString(columnIndex);
cursor.close();
FixBitmap = BitmapFactory.decodeFile(ImagePath);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));
}
}
hope this helps you
I was using this code to allow the user to choose an image from a gallery app and to get that image afterwards.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImg.setImageBitmap(photo);
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri, projection, null, null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
mImg.setImageBitmap(bm);
mImg.setAlpha(1);
}
}
}
But in this answer here I was told that this code wont work in most android devices. Can I know why? And what is the best way to get an image chosen by the user.
I posted this in a separate question because it might be interesting.
By using bitmap, your image may looked blurry. If the image size too large, it will be a problem when you want to upload or retrieved them to(from) server. So uri is better than bitmap.
You may try below code and you will see the difference between bitmap and uri
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
else
{
imageView.setImageResource(R.mipmap.no_image);
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
Log.e("A", "AAA");
}
}
}
So I forked the cordova camera plugin because I wanted to modify it to return both a thumbnail and a regular size image when a picture is taken. I've never done android development before but this is what I have so far:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode / 16) - 1;
int destType = (requestCode % 16) - 1;
// if camera crop
if (requestCode == CROP_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bitmap thumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(croppedUri.toString()), 100, 100);
Uri thumbNailUri = getImageUri(this.cordova.getActivity().getApplicationContext(), thumbImage);
JSONArray imageArray = new JSONArray();
imageArray.put(croppedUri.toString());
imageArray.put(thumbNailUri.toString());
this.callbackContext
.success(imageArray);
croppedUri = null;
}// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = android.provider.MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
The problem is the application crashes when executing this code. It seems that the call BitmapFactory.decodeFile(croppedUri.toString()) returns a null value.
All the code I'm working with is here within the repo I linked above. All I'm trying to do is return the image paths to both the regular size image and the thumbnail.