Capturing and storing photo not working - Android - android

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

Related

How I can resize images taken from the Gallery?

I'm trying to:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, RESULTADO_GALERIA);
.
.
.
String imgPath = data.getDataString(); // return something like "/external/images/media/13852"
BitmapFactory.decodeFile(imgPath); // allways null...
I also tried:
File bitmapFile = new File(Environment.getExternalStorageDirectory()
+ "/" + imgPath);
String aux = bitmapFile.getAbsolutePath(); // /storage/sdcard0/external/images/media/13852
BitmapFactory.decodeFile(bitmapFile.getAbsolutePath()); // NULL
An the result it's the same
The olny thing work's for me is put the path manually...
File file = new File("/storage/sdcard0/DCIM/Camera/"+"IMG_20140506_101341.jpg"); // nothing to do with the path obtained by code...
BitmapFactory.decodeFile(bitmapFile.getAbsolutePath()); // OK
How can I get the REAL path for a image of the gallery? Other ideas to resize them?
Thanks!
I have demonstrate to Both the case
1) capture Photo from camera
2) Take a photo from gallary
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;
}

Upload image from gallery in android

I want to get an image from a gallery to show in imageview. Intent returned the path as "Content" in Sony mobile. I can get it using this code.
Uri image=data.getData();
But when I am using a Samsung mobile, intent returned this.
Intent { act=file:///mnt/sdcard/Pictures/Education%20App/IMG_20140513_160840.jpg (has extras) }
I used same code to get the URI, but the returned value is null. I don't know how to get this Uri.
I have demonstrate to Both the case
1) capture Photo from camera
2) Take a photo from gallary
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;
}

How to get preview of captured image through camera intent in 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);
}

How to get image name of after taking photo or sd card in Android

I am little confusion about how to get image name, when taking photo from camera(Current Click image) or sd card(Already cliked or in the sd card image).Could you please help me out how to get image name.
if (requestCode == CAMERA_REQUEST) {
ImageView profImage;
Bitmap photo = (Bitmap) data.getExtras().get("data");
Bitmap scaledphoto = Bitmap.createScaledBitmap(photo, height, width,
true);
profImage.setImageBitmap(scaledphoto);
//How to get name here
}
Now , Here How to get ImageName for propose of saving image on database.
Or
Imageview test=(Imageview) findViewById(R.id.testimage);
test.setImageResource(R.drawable.androidimage);
So, I want get name of image, Here image name is androidimage.SO How to get imagename.
You can pass the Bitmap to this method to get Image Uri.
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(),
inImage, "Title", null);
return Uri.parse(path);
}
Finally you can set the image to image view with
imageView.setImageUri(mUri);
Please use the following code.
public class UploadImageActivity extends Activity {
private final int CAMERA_PICTURE = 1;
private final int GALLERY_PICTURE = 2;
private ImageView userPictureImageView;
private Intent pictureActionIntent = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
userPictureImageView = (ImageView) findViewById(R.id.imageView1);
userPictureImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE) {
Uri uri = data.getData();
if (uri != null) {
// User had pick an image.
Cursor cursor = getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
File photos = new File(imageFilePath);
Bitmap b = decodeFile(photos);
b = Bitmap.createScaledBitmap(b, 150, 150, true);
userPictureImageView.setImageBitmap(b);
cursor.close();
}
else {
Toast toast = Toast.makeText(this, "No Image is selected.", Toast.LENGTH_LONG);
toast.show();
}
}
else if (requestCode == CAMERA_PICTURE) {
if (data.getExtras() != null) {
// here is the image from camera
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
userPictureImageView.setImageBitmap(bitmap);
}
}
}
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
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++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {
}
return null;
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent, CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
}
Dont forget to add the camera permission in your manifest file.
Updated Code
Gallery :
Intent photoPickerIntent = new Intent(
Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, CAMERA_PIC_REQUEST);
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
Uri selectedImage = data.getData();
String filePath = getRealPathFromURI(selectedImage);
// used in show HD images
BitmapFactory.Options bounds = new BitmapFactory.Options();
// divide bitmap to 4 sample size it can be 2rest(2,4,8 etc)
bounds.inSampleSize = 4;
// get bitmap from bounds and file path
Bitmap bmp = BitmapFactory.decodeFile(filePath, bounds);
imageView.setImageBitmap(bmp);
Uri selectedImageUri1 = data.getData();
String path = getRealPathFromURI(selectedImageUri1);
File file = new File(path);
textView.setText(file.getName());
}
}
public String getRealPathFromURI(Uri contentUri) {
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();
return cursor.getString(column_index);
}

Camera activity returning null android

I am building an application where I want to capture an image by the default camera activity and return back to my activity and load that image in a ImageView. The problem is camera activity always returning null. In my onActivityResult(int requestCode, int resultCode, Intent data) method I am getting data as null. Here is my code:
public class CameraCapture extends Activity {
protected boolean _taken = true;
File sdImageMainDirectory;
Uri outputFileUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameracapturedimage);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName");
startCameraActivity();
} catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
protected void startCameraActivity() {
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
{
if(resultCode==Activity.RESULT_OK)
{
try{
ImageView imageView=(ImageView)findViewById(R.id.cameraImage);
imageView.setImageBitmap((Bitmap) data.getExtras().get("data"));
}
catch (Exception e) {
// TODO: handle exception
}
}
break;
}
default:
break;
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}
}
Am I doing anything wrong?
You are getting wrong because you are doing it wrong way.
If you pass the extra parameter MediaStore.EXTRA_OUTPUT with the camera intent then camera activity will write the captured image to that path and it will not return the bitmap in the onActivityResult method.
If you will check the path which you are passing then you will know that actually camera had write the captured file in that path.
For further information you can follow this, this and this
I am doing it another way. The data.getData() field is not guaranteed to return a Uri, so I am checking if it's null or not, if it is then the image is in extras. So the code would be -
if(data.getData()==null){
bitmap = (Bitmap)data.getExtras().get("data");
}else{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
I am using this code in the production application, and it's working.
I had a similar problem. I had commented out some lines in my manifest file which caused the thumbnail data to be returned as null.
You require the following to get this to work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
I hope this resolves your issue
If you phone is a Samsung, it could be related to this http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/
There is another open question which may give additional information
If you are using an ImageView to display the Bitmap returned by Camera Intent
you need to save the imageview reference inside onSaveInstanceState and also restore it later on inside onRestoreInstanceState. Check out the code for onSaveInstanceState and onRestoreInstanceState below.
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
String mCurrentPhotoPath;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageView = (ImageView) findViewById(R.id.imageView1);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void startCamera(View v) throws IOException {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
photoFile = createImageFile();
//intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
&& resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
System.out.println(imageBitmap);
imageView.setImageBitmap(imageBitmap);
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
System.out.println(mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
System.out.println(mCurrentPhotoPath);
imageView = (ImageView) findViewById(R.id.imageView1);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
System.out.println(mCurrentPhotoPath);
imageView = (ImageView) findViewById(R.id.imageView1);
}
}
after many search :
private static final int TAKE_PHOTO_REQUEST = 1;
private ImageView mImageView;
String mCurrentPhotoPath;
private File photoFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saisir_frais);
mImageView = (ImageView) findViewById(R.id.imageViewPhoto);
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST && resultCode == RESULT_OK) {
// set the dimensions of the image
int targetW =100;
int targetH = 100;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoFile.getAbsolutePath(), bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
// stream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath(),bmOptions);
mImageView.setImageBitmap(bitmap);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
photoFile = createImageFile();
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
} catch (IOException e) {
e.printStackTrace();
}
}
Try following code
{
final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (fullPath.contains("DCIM")) {
//get bitmap from fullpath here.
return;
}
}
while (imageCursor.moveToNext());
While taking from camera few mobiles would return null. The below workaround will solve. Make sure to check data is null:
private int CAMERA_NEW = 2;
private String imgPath;
private void takePhotoFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAMERA_NEW);
}
// to get the file path
private 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;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_NEW) {
try {
Log.i("Crash","CAMERA_NEW");
if(data!=null &&(Bitmap) data.getExtras().get("data")!=null){
bitmap = (Bitmap) data.getExtras().get("data");
personImage.setImageBitmap(bitmap);
Utils.saveImage(bitmap, getActivity());
}else{
File f= new File(imgPath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize= 4;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
personImage.setImageBitmap(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
You can generate bitmap from the file that you send to camera intent. Please use this code...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
{
if(resultCode==Activity.RESULT_OK)
{
int orientation = getOrientationFromExif(sdImageMainDirectory);// get orientation that image taken
BitmapFactory.Options options = new BitmapFactory.Options();
InputStream is = null;
Matrix m = new Matrix();
m.postRotate(orientation);//rotate image
is = new FileInputStream(sdImageMainDirectory);
options.inSampleSize = 4 //(original_image_size/4);
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
// set bitmap to image view
//bitmap.recycle();
}
break;
}
default:
break;
}
}
private int getOrientationFromExif(String imagePath) {
int orientation = -1;
try {
ExifInterface exif = new ExifInterface(imagePath);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_NORMAL:
orientation = 0;
break;
default:
break;
}
} catch (IOException e) {
//Log.e(LOG_TAG, "Unable to get image exif orientation", e);
}
return orientation;
}
File cameraFile = null;
public void openChooser() {
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,new Intent[]{takePhotoIntent});
startActivityForResult(chooserIntent, SELECT_PHOTO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
if (selectedImage != null) {
//from gallery
} else if (cameraFile != null) {
//from camera
Uri cameraPictureUri = Uri.fromFile(cameraFile);
}
}
break;
}
}
Try this tutorial. It works for me and use permission as usual in manifesto & also
check permission
https://androidkennel.org/android-camera-access-tutorial/
After a lot of vigorous research I finally reached to a conclusion.
For doing this, you should save the image captured to the external storage.
And then,retrieve while uploading.
This way the image res doesnt degrade and you dont get NullPointerException too!
I have used timestamp to name the file so we get a unique filename everytime.
private void fileChooser2() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName=getPictureName();
fi=pictureName;
File imageFile=new File(pictureDirectory,pictureName);
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
startActivityForResult(intent,PICK_IMAGE_REQUEST2);
}
Function to create a file name :
private String getPictureName() {
SimpleDateFormat adf=new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = adf.format(new Date());
return "The New image"+timestamp+".jpg";//give a unique string so that the imagename cant be overlapped with other apps'image formats
}
and the onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PICK_IMAGE_REQUEST2 && resultCode==RESULT_OK )//&& data!=null && data.getData()!=null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
File picDir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile=new File(picDir.getAbsoluteFile(),fi);
filePath=Uri.fromFile(imageFile);
try {
}catch (Exception e)
{
e.printStackTrace();
}
StorageReference riversRef = storageReference.child(mAuth.getCurrentUser().getUid()+"/2");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
Edit: give permissions for camera and to write and read from storage in your manifest.

Categories

Resources