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
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 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 last night i thought i had my app working, however, this morning the gremlins have invaded and have now made a function of my app not work correctly.
Basically, a button allows the user to take a photo, and have that photo displayed in an Imageview, then attach the image to an email.. It lets me take the photo, and it is still present as an attachment, but the preview in the image view is completely empty.
Can anybody see what is going on?
Hoon_Image = (ImageView) findViewById(R.id.CapturedImage);
button_take_photo = (Button)findViewById(R.id.btn_take_photo);
button_take_photo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
f = createImageFile();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
public File getAlbumDir()
{
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
"BAC/"
);
// Create directories if needed
if (!storageDir.exists()) {
storageDir.mkdirs();
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName =getAlbumDir().toString() +"/image.jpg";
File image = new File(imageFileName);
return image;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_REQUEST ){
Bitmap photo = BitmapFactory.decodeFile(f.getAbsolutePath());
Hoon_Image.setImageBitmap(photo);
}
}
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
//DEBUG PURPOSE - you can delete this if you want
if(selectedImagePath!=null)
System.out.println(selectedImagePath);
else System.out.println("selectedImagePath is null");
if(filemanagerstring!=null)
System.out.println(filemanagerstring);
else System.out.println("filemanagerstring is null");
//NOW WE HAVE OUR WANTED STRING
if(selectedImagePath!=null)
System.out.println("selectedImagePath is the right one for you!");
else
System.out.println("filemanagerstring is the right one for you!");
}
Bitmap photo = BitmapFactory.decodeFile(selectedImagePath);
Hoon_Image.setImageBitmap(photo);
Photo_Selected = 1;
}
}
What I've done for the image to be shown in the ImageView in Android is to use a method decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) that decodes the File object with a required width and height. Below is a sample code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_OK) {
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "image.jpg");
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(),
600, 450);
imageView.setImageBitmap(bitmap);
}
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth,
int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
// Query bitmap without allocating memory
options.inJustDecodeBounds = true;
// decode file from path
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
// decode according to configuration or according best match
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float) height / (float) reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
// if(Math.round((float)width / (float)reqWidth) > inSampleSize) //
// If bigger SampSize..
inSampleSize = Math.round((float) width / (float) reqWidth);
}
// if value is greater than 1,sub sample the original image
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
So i found to what i was doing wrong - derp moment coming right up.
this section of code:
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_REQUEST ){
it was just looking of ok result (which happened both for selecting a photo and taking a photo successfully) rather than first looking for the RequestCode.
rearranging the code to this worked:
if(requestCode == CAMERA_REQUEST ) {
if (resultCode == RESULT_OK){
Bitmap photo = BitmapFactory.decodeFile(f.getAbsolutePath());
Hoon_Image.setImageBitmap(photo);
I'm using these codes to capture and store an image on a button click.
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
destination = new File(Environment
.getExternalStorageDirectory(),
preferences.getSelectedItem().getItemNo() + "_"
+ preferences.getSelectedItem().getChasisNo() + "_up");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(destination));
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
FileInputStream in;
try {
in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imgPath = destination.getAbsolutePath();
// Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Image saved", "Image saved at " + imgPath);
upItem.setUpPhotoURL(String.valueOf(imgPath));
isPhotoAttached = true;
}
}
But when I capture the photo and try to confirm it, app does nothing. Cancelling and retaking options work perfectly but confirming the taken image doesn't do anything. Can anyone point me where the problem lies here?
added this permission in your manifest file
<uses-feature android:name="android.hardware.camera" />
.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA};
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
Toast.makeText(this, capturedImageFilePath, Toast.LENGTH_SHORT).show();
}
Try this
String mCurrentPhotoPath = destination.getAbsolutePath();
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO_CODE: {
if (resultCode == RESULT_OK) {
if (mCurrentPhotoPath != null) {
getBitmap(mCurrentPhotoPath);
}
}
break;
}
default:
break;
}
}
private Bitmap getBitmap(String mCurrentPhotoPath) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = imageView.getMeasuredWidth();
int targetH = imageView.getMeasuredHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
Bitmap oribitmap = BitmapFactory.decodeFile(mCurrentPhotoPath,
bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 3;
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
return oribitmap = BitmapFactory.decodeFile(mCurrentPhotoPath,
bmOptions);
}
This permission in your manifest file
<uses-feature android:name="android.hardware.camera" />
I think this is not working because the name of the image is too big. When I changed this
destination = new File(Environment.getExternalStorageDirectory(),
preferences.getSelectedItem().getItemNo() + "_"
+ preferences.getSelectedItem().getChasisNo() + "_up");
to this
destination = new File(Environment.getExternalStorageDirectory(),
preferences.getSelectedItem().getChasisNo() + ".jpg");
I'm not sure if there's such a thing as the image name being too big, but this change is working for me
I am trying to get an image from a camera using on activity result. It is working properly on android 4.2. But I can't get the image from android 2.36.
Can anyone please help me?
Part of source code is attached below:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 2) {// image from camera
photo = (Bitmap) data.getExtras().get("data");
selectedImageUri = data.getData();
photo = decodeUri(selectedImageUri);
test.setImageBitmap(photo);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(
getContentResolver().openInputStream(selectedImage), null, o);
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(
getContentResolver().openInputStream(selectedImage), null, o2);
}
Use this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 2) {// image from camera
if (resultCode == Activity.RESULT_OK) {
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try {
mPhoto = android.provider.MediaStore.Images.Media
.getBitmap(cr, mUri);
Bitmap useThisBitmap = Bitmap.createScaledBitmap(mPhoto,
mPhoto.getWidth(), mPhoto.getHeight(), true);
test.setImageBitmap(useThisBitmap);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
} else {
Toast.makeText(this,
resultCode + "" + "=" + Activity.RESULT_CANCELED,
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It looks to me like this line is not needed:
photo = (Bitmap) data.getExtras().get("data");