How to get preview of captured image through camera intent in android - android

Hi am capturing an image through camera intent it works good but my problem is that am not getting preview of that image
my requirement is very simple, after clicking of photo through camera it must ask me to SAVE or DISCARD this image if i press SAVE then it get save into sd card thats it...
here is my code
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
capturedFile = new File(Environment.getExternalStorageDirectory(),
"tmp_nookster_profilepic"
+ String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(capturedFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA_NO_CROP);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA_NO_CROP: {
iu.SaveCapturedImage(BitmapFactory.decodeFile(capturedFile
.getAbsolutePath()));
try {
if (capturedFile.exists())
capturedFile.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
break;
here "iu" is object of ImageUtility class and "SaveCapturedImage" is method to store that captured image in SdCard

You can get a preview of the captured File as this:
Bitmap getPreview(File image) {
final int THUMBNAIL_SIZE = 72;
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
then you can show the Bitmap in an ImageView and present the user with Save/Delete buttons.

You have to remove line from your code.
if (resultCode != RESULT_OK)
return;
Use following code :
if (resultCode == RESULT_OK)
{
try
{
Bitmap bitmap=null;
String imageId = convertImageUriToFile(imageUri,AddRecipes.this);
bitmap = BitmapFactory.decodeFile(imageId);
}}
public static String convertImageUriToFile (Uri contentUri, Activity activity)
{
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader cursorLoader = new CursorLoader(activity.getApplicationContext(),contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Related

Share photo on Facebook Android SDK

I'm trying to share a photo on Facebook with Android SDK.
The problem is that my Bitmap image is null. This is my code:
public void sharePhoto(View view) {
if (Session.getInstance().getUserFace().getBestphoto() == null) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
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};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Log.d("picture path", picturePath);
BitmapFactory.Options options = new BitmapFactory.Options();
try {
Bitmap image = BitmapFactory.decodeFile(picturePath, options);
uploadPhoto(image);
} catch (OutOfMemoryError e) {
try {
options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap image = BitmapFactory.decodeFile(picturePath, options);
uploadPhoto(image);
} catch (Exception ex) {
Log.e("EXCEPTION", ex.toString());
}
}
}
}
private void uploadPhoto(Bitmap image) {
Log.d("Image", "" + image);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareDialog.show(MainActivity.this, content);
}
You can try getting the bitmap from InputStream instead. Use this,
BitmapFactory.decodeStream(resolver.openInputStream(uri), null, options);
where resolver is your ContentResolver and uri is returned by data.getData();
You won't need to query the database, unless you wanna check for any FileNotFoundException.
File file = new File(picturePath);
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
try {
Bitmap image = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(imageUri));
uploadPhoto(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Your "picturePath" cursor from MediaStore, it maybe like this /storage/emulated/0/DCIM/Camera/IMG20200513xx.jpg.
You can try to changing path to content URI (file:///storage/emulated/0/DCIM/Camera/IMG20200513xx.jpg).
Use content provider's getContentResolver() to open your image. Then decode image to Bitmap.

Android Camera Intent crashes with Android L

My app is working properly on all api till Kitkat but it's not working in lollipop. The moment i clicks for capturing a photo using camera in my app, it crashes.
cam.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
This is my onActivityResult()
case CAMERA_REQUEST: {
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();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
options.inSampleSize = calculateInSampleSize(options,200,100);//512 and 256 whatever you want as scale
options.inJustDecodeBounds = false;
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath,options);
File pngDir = new File(Environment.getExternalStorageDirectory(),"PicUploadTemp");
if (!pngDir.exists()) {
pngDir.mkdirs();
}
File pngfile = new File(pngDir,"texture1.jpg");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(pngfile);
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 50,fOut);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromPath(pngfile.getPath().toString());
rlLayout.setBackground(d);
yourSelectedImage.recycle();
// resizedBitmap.recycle();
xfile = pngfile;
}
break;
I want to compress the image and this above code is working amazingly for gingerbread, ICS , kitkat but not for Android L
I am getting null pointer Exception
Please suggest me some solution
Thanks in advance
Cannot really say anything about this without the logcat output, It may be becoming null in as a result of you using on of the deprecated method in the BitmapFacotry class.
Define these globally in your activity,
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
private static final int CAMERA_REQUEST = 1888;
in button click call your camera intent like this
startActivityForResult(cameraIntent, CAMERA_REQUEST);
make sure to use
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
use this to retrieve photo
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == getActivity().RESULT_OK) {
//get photo
Bitmap photo = (Bitmap) data.getExtras().get("data");
}

Cant able to capture images

public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.textView7)
{
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
}
catch(ActivityNotFoundException anfe)
{
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_CAPTURE){
picUri = data.getData();
performCrop();
}
else if(requestCode == PIC_CROP){
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView)findViewById(R.id.imageView1);
picView.setImageBitmap(thePic);
}
else if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
iv1.setImageURI(selectedImageUri);
}
}
}
private void performCrop(){
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, PIC_CROP);
}
catch(ActivityNotFoundException anfe){
Toast toast = Toast.makeText(this, "Mobile doesnot support this feature",Toast.LENGTH_SHORT);
toast.show();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
i tried to capture an image using this by clicking on button doesnt shows anything by clicking on it
I have created a button to capture the image but it shows error!!
please help
i am a newbie and wish to learn
Try this is working like charm with me
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
btnGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
}
});
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
Add below two lines in your manifest.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

Android - Camera activity gets opened instead of picture gallery

I've created an activity that allows the user to add a picture to an ImageView in that activity. I've created a button, that opens a context menu for the activity and gives the user options to either pick a picture from the gallery or take a picture with camera.
If I choose the first option - to pick a picture from the gallery, it works without problems. Gallery is opened, I pick the picture, my activity is resumed and the picture is added to the ImageView.
Strange things start happening after choosing the second option, taking the picture and resuming to my activity:
If I open the context menu again and try to open the gallery, camera
activity gets opened instead
I close the camera activity and resume to my activity, "Complete action using" dialog is shown
I open the gallery, pick a picture and NullPointerException is thrown
Why am I having this behavior and an exception? I've tried searching for similar topics but haven't found a solution.
Below are the methods for my activity
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
switch(item.getItemId()) {
case R.id.cm_Select_picture: {
// TODO open gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), RC_SELECT_PICTURE);
}
case R.id.cm_Take_picture: {
// TODO open camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, RC_TAKE_PICTURE);
}
default: return false;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch(requestCode) {
case RC_SELECT_PICTURE: {
Log.d(TAG, "Case select picture");
Uri selectedImageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri
, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap pic = BitmapFactory.decodeFile(filePath);
goodsImage.setImageBitmap(pic);
}
case RC_TAKE_PICTURE: {
Log.d(TAG, "Case take picture");
if(data.getExtras().get("data") != null) {
Bitmap pic = (Bitmap) data.getExtras().get("data");
goodsImage.setImageBitmap(pic);
}
}
}
}
}
04-26 01:34:59.529: E/AndroidRuntime(20531): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=Intent { dat=content://media/external/images/media/9 }} to activity {com.forestassistant/com.statistics.GoodsActivity}: java.lang.NullPointerException
i used to call camera activity from my activity, and it worked well, here is my code:
setMediaUri(getNewMediaFilePath(actOwner.getContentResolver()));
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getMediaUri());
startActivityForResult(cameraIntent, CAMERA_CAPTURE_REQUEST_CODE);
and when result callback
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK
&& requestCode == CAMERA_CAPTURE_REQUEST_CODE) {
Drawable toRecycle= imgView.getDrawable();
if (toRecycle != null) {
((BitmapDrawable)imgView.getDrawable()).getBitmap().recycle();
}
mImg = decodeFileIntoRequiredSize(getPath(getMediaUri(),this), requiredSizeForImage);
imgView.setImageBitmap(mImg);
}
public Bitmap decodeFileIntoRequiredSize(String filePath,int requiredSize){
Bitmap b = null;
try {
File f = new File(filePath);
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > requiredSize || o.outWidth > requiredSize) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(requiredSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (IOException e) {
}
return b;
}
public String getPath(Uri uri,Activity act) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = act.managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public Uri getNewMediaFilePath(ContentResolver contentResolver) {
ContentValues values = new ContentValues();
//create the directory
// /mnt/sdcard/DCIM/Camera/IMG_20111101_111922.jpg
String cameraDir = "/Camera";
//File dir1 = act.getExternalFilesDir(Environment.DIRECTORY_DCIM);
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()+cameraDir);
if(!dir.exists()) dir.mkdir();
//use date as filename
String name = "IMG_" + (String) android.text.format.DateFormat.format("yyyyMMdd_hhmmss",new Date());
String path = dir.getPath()+File.separator + name;
values.put(MediaStore.MediaColumns.TITLE, name);
values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
Uri base = null;
path += ".jpg";
base = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, path);
return contentResolver.insert(base, values);
}
Hope this help you.

Why i am not able to take image from camera but can able to get image from Gallery in android?

I am using this code to fetch Image from gallery:
fromGalleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasPictureDialog.dismiss();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
//startActivity(intent);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),10);
//finish();
}
});
And to take image from camera i use this code:
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getTempFile(Context context){
//it will return /sdcard/image.tmp
//final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName());
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
And common code for onActivityResult is:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
//Bitmap croppedImage = BitmapFactory.decodeFile(imagePath);
tempBitmap = BitmapFactory.decodeFile(imagePath);
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
}
if(resultCode == RESULT_OK && requestCode==TAKE_PHOTO_CODE){
final File file = getTempFile(this);
try {
tempBitmap = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now with using this code i am drawing the image on canvas:
if(!(imagePath==null))
{
//tempBitmap = BitmapFactory.decodeFile(imagePath);
//photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
canvas.drawBitmap (photoBitmap,0, 0, null);
}
But with that use, I am able to get Image from gallery but not from the camera. Why ??
Whats wrong in my code ??
Thanks.
Well, I have solve this problem for my own way.
There is a logical mistake. I have taken the if condition on imagePath variable which can not works for the taking image from camera.
I have taken one boolean Variable and set it for Taking Image from Camera and it works for me.
Anyway, Thanks for the Comments and help.
Thanks.

Categories

Resources