Captured image does not get saved on the device - android

I am trying to save a camera captured image on the device. But it does not get saved.
//---manifest
<uses-permission android:name="ANDROID.PERMISSION.CAMERA" />
<uses-permission android:name="ANDROID.PERMISSION.WRITE_EXTERNAL_STORAGE" />
I use the following code:
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File outFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "myimage.jpg");
FileOutputStream fos = new FileOutputStream(outFile);
photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
getImages();

See what i have done in my code for saving the captured image.
/*************************** Camera Intent Start ************************/
// Define the file-name to save photo taken by Camera activity
String fileName = "Camera_Example.jpg";
// Create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
// imageUri is the current activity attribute, define and save it for later usage
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
/**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
onActivityResult method is here:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
/*********** Load Captured Image And Data Start ****************/
String imageId = convertImageUriToFile(imageUri, CameraActivity);
// Create and excecute AsyncTask to load capture image
new LoadImagesFromSDCard().execute("" + imageId);
/*********** Load Captured Image And Data End ****************/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
}

// don't use data.getData() as it return null in some device.
So use the cursor for getting captured Image.
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (resultData != null) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
String imagePath = cursor.getString(column_index_data);
Bitmap bitmapImage = BitmapFactory.decodeFile(imagePath );
imageView.setImageBitmap(bitmapImage );
}

Related

Returning Imageuri=null (but data extras) from camera capture

while debugging the below code, i am getting the value of picUri as null and i can see as picUri=null data:"Intent" {act=inline-data (has extras)}" in trace. Why does picUri is not having the corresponding uri and have data extras?
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
try {
// use standard intent to capture an image
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData();
}
}
}
Here you pass the camera Intent
private void INTENTCAMERA() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
And after that captured your image
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);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
Log.e("ResultcapturedImage-->",mImageCaptureUri);
}
}
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);
}
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 have received the data in Bundle in onactivityresult and stored it into a file and got the uri from that file as shown below.
Bundle extras = data.getExtras();
Bitmap var_Bitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
var_Bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
try {
OutputStream out;
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"macro"+File.separator);
createDir.mkdir();
File file = new File(root + "macro" + File.separator +"macro.jpg");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
picUri= Uri.fromFile(file);
} catch (IOException e) {
// e.printStackTrace();
}

Unable to use intent for CAMERA

In my application ,on clicking Image View i want to start Camera which will capture image and display it in another image view.My code is given below:
//On clicking Camera
iv_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Log.e("Result Code", String.valueOf(resultCode));
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri selectedImageUri = data.getData();
Log.e("ImageUri", String.valueOf(selectedImageUri));
String realPath = getRealPathFromURI(selectedImageUri);
Log.e("Real Path", realPath);
imgProfilePic.setImageBitmap(photo);
}
}
}
//Get real path form Uri
public String getRealPathFromURI(Uri contentUri) {
try {
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);
} catch (Exception e) {
return contentUri.getPath();
}
}
My problem is that ,on some mobiles it is working fine but on some it is not. For example: If i am testing my application using on my phone Yu Yureka having Lollipop ,it is giving me data as null.Also when the orientation changes,application is crashing .Please help me to fix the issue.
In your Manifest file use these permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Implement from this Simple Code Example this is my working example code
public void CameraClick(View v) {
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// creating Dir to save clicked Photo
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cam_Intent");
myDir.mkdirs();
// save clicked pic to given dir with given name
File file = new File(Environment.getExternalStorageDirectory(),
"/cam_Intent/MyPhoto.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent, TAKE_PIC);
}
Bitmap bitmap = null;
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (requestCode == TAKE_PIC && resultCode==RESULT_OK) {
String uri = outPutfileUri.toString();
Log.e("uri-:", uri);
Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
//Bitmap myBitmap = BitmapFactory.decodeFile(uri);
// mImageView.setImageURI(Uri.parse(uri)); OR drawable make image strechable so try bleow also
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outPutfileUri);
Drawable d = new BitmapDrawable(getResources(), bitmap);
mImageView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
}

onActivityResult is not calling after taking camera picture

I am doing an android app, in which I have a functionality that, I need to open camera and take a picture. After taking picture onActivityResult is not called. my screen remains only in camera state.
My code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaFile = new File(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
Uri imageUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 1);
onActivityResult code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && !data.toString().equalsIgnoreCase("Intent { }"))
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
}
onActivityResult is probably called, but the statements inside your if statement and switch/case statements are not being executed, because they are never reached.
The code below includes two methods takePhoto and onActivityResult, is very short and works perfectly. Take a look at it, it probably will help you!
public void takePhoto(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
You can run your application in debug mode, after putting a breakpoint in onActivityResult method,
if it's stopping there after getting from the Camera then it's being called successfully.
and you could just change the if statement you're using making your code like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null && resultCode = RESULT_OK)
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
}
and note that it is more recommended to using final ints as the request code instead of rewriting them everytime they're needed
like :
private final int START_CAMERA_REQUEST_CODE = 1;
I think this may be help you
Follow Below Code step by step and compare with your code to avoid null exception
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
1 OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1)
onCaptureImageResult(data);
}
}
2
onCaptureImageResult
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
Uri tempUri = getImageUri(getApplicationContext(), thumbnail); // call getImageUri
File finalFile = new File(getRealPathFromURI(tempUri));
file_path = finalFile.getPath().toString(); // your file path
imgview.setImageBitmap(thumbnail);
// this code will get your capture image bitmap}
3 getImageUri
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); // your capture image URL code
return Uri.parse(path);
}
Using this code your screen will not remain more on camera state it will finish and image will be load as well you get image URL.
Bitmap mBitmap = BitmapFactory.decodeFile(imgPath);
pass Image path which you create from URI.
Probably, your activity is reloaded after camera is finished, but your code is not prepared to such situation.
See Android startCamera gives me null Intent and ... does it destroy my global variable?.
I think onActivity is called but it doesn't go into the if condition
Check only for null in if condition:
if (data != null )
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
From where you are calling startActivityForResult(intent, 1),
and where you Overriding onActivityResult() ?
I mean if you call startActivityForResult() from Frgment then you should override onActivityResult() in fragment it self, same applies to Activity also.

Camera Intent returns no file path

I have a problem with my camera Intent. It saves the pictures to the storage, but it doesn't return the file path to my activity. When i remove the EXTRA_OUTPUT it returns the file path, but then the images have just a very small size. Is there any solution to get the pictures with original size without using EXTRA_OUTPUT?
Here is my code:
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
preinsertedUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, preinsertedUri);
startActivityForResult(intent, OPEN_CAMERA);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case OPEN_CAMERA:
if (resultCode == RESULT_OK && data != null) {
Uri imageUri = null;
imageUri = data.getData();
if(imageUri == null && preinsertedUri != null){
imageUri = preinsertedUri;
}
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filePath = cursor.getString(columnIndex);
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(filePath);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Try this it might help you.
When I capture the photo from camera so I implement a logic using Cursor and iterate the cursor and get the last photo path which is capture from camera.
It give the path of last capture photo from camera.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}

Display the latest picture taken in the image view layout in android

I am working on a app that takes a picture with my camera and shows it in my image view layout.So any one can tell me how to access the latest picture taken and display it.
i got the solution if anyone have the same problem u can consult this
public void click1(View v){
//define the file-name to save photo taken by Camera activity
capturedImageFilePath=null;
fileName = System.currentTimeMillis()+"";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(imageUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
capturedImageFilePath = cursor.getString(column_index_data);
imageFile = new File(capturedImageFilePath);
if(imageFile.exists()){
Bitmap bm = BitmapFactory.decodeFile(capturedImageFilePath);
image.setImageBitmap(bm);}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
}

Categories

Resources