Camera Capture Image is not clear(Blurry) in Android - android

I Have a Problem with the Camera Capture Image.its set blurry.
I searched lots of but i can't Get Solutions
I don't know How to solve issue
Here is My Code Which i Used For Camera Capture Image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 0, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
img1.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
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);
img1.setImageBitmap(bm);
}
The Gallery Image Set Good in Imageview But Its Only Happen with the CameraCapture Imageview
Camera Capture Image is not clear(Blurry) in Android
Help Me for this issue.
Thanks In Advance

Your problem is here
thumbnail.compress(Bitmap.CompressFormat.JPEG, 0, bytes);
Second paramater in .compress() method is quality which can be in range 0..100.
You have set it to 0 -> maximum compression.
Change the value to a higher value.

What you are doing is getting thumbnail nail out of intent data that's why it is blurry
Try This :
File mImageFile is path where you want to store you camera image file.
mImageFile= new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "temp.png");
Uri tempURI = Uri.fromFile(mImageFile);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
activity.startActivityForResult(i, CHOOSE_CAMERA_RESULT);
then in your onActivityResult
#Override
public void onActivityResultRAW(int requestCode, int resultCode, Intent data)
{
super.onActivityResultRAW(requestCode, resultCode, data);
switch(requestCode)
{
case CHOOSE_CAMERA_RESULT:
{
if (resultCode == RESULT_OK)
{
// here you image has been save to the path mImageFile.
Log.d("ImagePath", "Image saved to path : " + mImageFile.getAbsoultePath());
}
}
break;
}
}

When you try to get bitmap from data.getExtras object in onActivityResult then it returns bitmap with low quality, below solution is complete followup Android Documentation. Don`t forget to write permission in Manifest.
lateinit var currentPhotoPath: String
var photoFile: File? = null
private fun takePhotoFromCamera() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.also { takePictureIntent ->
photoFile = try {
createImageFile()
} catch (ex: IOException) {
null
}
photoFile?.also {
fileUri = FileProvider.getUriForFile(
this, "com.example.fileprovider",
it
)
AppLogger.d("asad_fileUri", "$fileUri")
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
startActivityForResult(takePictureIntent, CommonUtils.CAMERA)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
try {
if (requestCode == CommonUtils.CAMERA) {
galleryAddPic()
setPic()?.let {
fileUri = getImageUri(this, it)
}
postImagesAdapter.addItems(
listOf(PostImagesModel(fileUri.toString(), false, fileUri)), false
)
} catch (e: Exception) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show()
}
super.onActivityResult(requestCode, resultCode, data)
}
// File path xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images"
path="/" />
</paths>
//AndroidManifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path"></meta-data>
</provider>
Take Photos

Related

how to capture an image using camera and save it server?

I want to capture an image using camera and store it in server. But I am getting null pointer exception after capturing the image. Completed mostly but this error is annoying. I am newbie to android i don't know why this error occurs. Need help thanks in advance
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CAMERA) {
if (data == null) {
Snackbar.make(parentView, R.string.string_unable_to_pick_image, Snackbar.LENGTH_INDEFINITE).show();
return;
}
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
// 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));
decodeFile(finalFile.toString());}}
**getImageUri method **
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, "aadhar", null);
return Uri.parse(path);//getting error here
}
getRealPathFromURI Method
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);
}
decodeFile Method
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
imageView.setImageBitmap(bitmap);
}
Error
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:475)
at android.net.Uri$StringUri.<init>(Uri.java)
at android.net.Uri.parse(Uri.java:437)
at com.androidbuts.ui.MainActivity.getImageUri(MainActivity.java:274)
at com.androidbuts.ui.MainActivity.onActivityResult(MainActivity.java:233)
at android.app.Activity.dispatchActivityResult(Activity.java:7139)
<!--First define permissions in Menifest-->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
// open camera as
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
// Then Retrive image As
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA && data != null) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File imageStorageDir = new File(Environment.getExternalStorageDirectory(),
getResources().getString(R.string.app_name));
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
imagePath = imageStorageDir + File.separator + "_NAME_YOU_WISH" + ".jpg";
fileImage = new File(imagePath); // FILE
try {
FileOutputStream out = new FileOutputStream(imagePath);
photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
if (fileImage != null) {
if (fileImage.isFile() && fileImage.exists()) {
// MyApplication.log(LOG_TAG, "onActivityResult() SHOWING IMAGE BY GLIDE, fileImage:-> " + fileImage.getAbsolutePath());
Glide.with(context)
.load(fileImage.getAbsoluteFile())
.asBitmap()
.placeholder(R.drawable.ic_broken_image)
.into(img_camera);
}
}
} catch (Exception e) {
//MyApplication.log(LOG_TAG, "onActivityResult() , Exception: " + e.getMessage());
}
}
}
// CALL THE FUNCTION TO SEND IMAGE TO SERVER
public void callSendCheckReport() {
MyApplication.showDialog(context, "Please Wait...");
HashMap<String, Object> map = new HashMap<>();
map.put("date", today);
map.put("salesman_id", MyApplication.get_session(MyApplication.SESSION_SALESMAN_ID));
if (actionStatus.equals("do_CHECK_IN")) { //// do_CHECK_IN, do_NO_CHANGE, do_CHECK_OUT
map.put("checkin", "yes");
map.put("in_time", checkTimeStamp);
if (fileImage != null)
map.put("in_image", new TypedFile("image*//*", fileImage));
}
RestClient.getWebServices().sendCheckReport(map,
new Callback<String>() {
#Override
public void success(String s, Response response) {
MyApplication.log(LOG_TAG, "Responce is----> " + s);
try {
JSONObject res = new JSONObject(s); // "status":"TRUE","message":"Shop Registered Successfully."}
String status = res.getString("status");
String message = res.getString("message");
MyApplication.stopLoading();
if (status.equals("TRUE")) {
if (fileImage.exists())
fileImage.delete();
}
showDialogBox(context, getResources().getString(R.string.app_name), message);
} catch (JSONException e) {
MyApplication.stopLoading();
// MyApplication.log(LOG_TAG + "RESPONSE JSONException ->" + e.getMessage());
}
}
#Override
public void failure(RetrofitError error) {
MyApplication.log(LOG_TAG + " RetrofitError ->" + error.getMessage());
MyApplication.stopLoading();
}
});
}

Camera Activity not returns path of image

I have task to capture image from camera and send that image to crop Intent. following is the code i have written
for camera capture
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
In on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData(); // picUri is global string variable
performCrop();
}
}
}
public void performCrop() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 3);
cropIntent.putExtra("aspectY", 2);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Your device doesn't support the crop action";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
I am getting different behaviours on different devices
In some devices i am getting error "couldn't find item".
In some devices after capturing image activity stuck and doesn't go ahead
I have also tried this
Please tell me the Right way to do this
You can by calling the intent like below:
int REQUEST_IMAGE_CAPTURE = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
((Activity) context).startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
And in your activity inside OnActivityResult you get the path like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
ESLogging.debug("Bytes size = " + attachmentBytes.length);
ESLogging.debug("FilePath = " + path);
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
ESLogging.error("FileNotFoundException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (IOException e) {
ESLogging.error("IOException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
}
}
}
//Declare this in class
private static int RESULT_LOAD_IMAGE = 1;
String picturePath="";
// write in button click event
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
//copy this code in after onCreate()
#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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.img); //place imageview in your xml file
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
write the following permission in manifest file
1.read external storage
2.write external storage
try this tutorial http://www.androidhive.info/2013/09/android-working-with-camera-api/ this will help you

Android IMAGE_CAPTURE always returns Activity.RESULT_CANCELED

I want to take a photo in my app. On the emulator everything works fine.
But on the tablet, the Intent immediately returns Activity.RESULT_CANCELED in onActivityResult. The picture is saved on the SD Card.
Here is the code for taking picture:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String tmpFile = CommonFunctions.generateRandomFileName() + ".jpg";
String fileName = CommonFunctions.getNoticeSavePath() + tmpFile;
System.out.println("Filename " + fileName);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(fileName)));
notice.setBild(tmpFile);
startActivityForResult(intent, RESULT_PICTURE);
Code for onActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_PICTURE:
System.out.println("ResultCode" + resultCode);
if (resultCode == Activity.RESULT_OK) {
}
else if (resultCode == Activity.RESULT_CANCELED){
notice.setBild("");
Toast.makeText(getBaseContext(), "Bild wurde nicht hinzugefĆ¼gt", Toast.LENGTH_LONG).show();
}
break;
}
}
Permissions are set:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
The result is always RESULT_CANCELED, but the photo is stored correctly on the sd card.
What could the problem be?
Do something like this
private static final int REQUEST_CAMERA = 1, SELECT_FILE = 2; //global
onresult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = null;
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 300, 200, true);
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Phoenix" + File.separator + "default";
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("endum_image_", f.toString()).commit();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE)
{
Uri selectedImageUri = data.getData();
//getRealPathFromURI(selectedImageUri);
String tempPath = getPath(selectedImageUri, Signup2Activity.this);
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("endum_image_", tempPath).commit();
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath,btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 300, 200, true);
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
}
}
imSex.setImageBitmap(bm);
flag= true;
}

Camera not working/saving when using Cache Uri as MediaStore.EXTRA_OUTPUT

I am trying to get the full image after taking a picture from a Fragment.
If I use the Uri from the file (Uri.fromFile(file)), the camera won't exit after taking the photo and tapping on the 'ok' button (looks like can't write to the Uri or who knows what).
Using the File String, in the form of '/data/data/com.package.bla/cache/img198346262jpg', it's not working as well (The file is there, but it's empty because the camera is not saving anything on it).
What I tried so far:
Deleting the file after creating it, as this example does. However, the file doesn't exist after the camera exits.
Added External Storage READ permission, just in case
So I have no idea why the image is not being saved and already spent/wasted a lot of time testing and figuring why it's not working.
Fragment:
private void launchCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File outputDir = getActivity().getCacheDir();
File file = null;
try {
file = File.createTempFile("img", "jpg", outputDir);
} catch (IOException e) {
e.printStackTrace();
}
if (file != null) {
mImageUri = Uri.fromFile(file); //using Uri is not even exiting the camera
//mImageUri = File.toString(); //If I use String instead of an Uri, it works better (ie, can accept camera photo)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(cameraIntent, RESULT_TAKE_IMAGE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Bitmap original = BitmapFactory.decodeFile(mImageUri.toString(), bounds);
}
}
Edited code, mImageUri. As explained, if I use Uri I can't even accept the photo in the camera app. Using a String will let me accept the photo, though the photo is not actually saved (ie the file has 0 bytes inside it).
EXPLANATION: The problem was related to saving into the cache directory. Maybe it's a bug, I am missing a permission or the camera app just can't save into your application private data directory. Adding Permission FLAG_GRANT_WRITE_URI_PERMISSION didn't solve it. Related posts: Store image from camera into private app cache directory AND Saving camera data to cache when launched via intent
UPDATE From Android 2.2 onwards getExternalCacheDir() method can be used instead of getCacheDir()
from android 26+ Uri.fromFile will not work, you should use File provider instead.
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
.........
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
res/xml/file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
</paths>
finally
final Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// output file
File path = new File(Environment.getExternalStorageDirectory(), "tmp.mp4");
// com.mydomain.fileprovider is authorities (manifest)
// getUri from file
Uri uri = FileProvider.getUriForFile(this, "com.mydomain.fileprovider", path);
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(takeVideoIntent, 99);
tested on android 8.0 and 5.1.1
Update: on some device built-in camera would not support for EXTRA_OUTPUT, so if you want to work on all devices, build your own camera module.
Why not saving it in a new File
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
mImageUri = Uri.fromFile(sdImageMainDirectory);
And then pass that uri to the intent
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
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;
}

Android camera capture activity returns null Uri

This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
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();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}

Categories

Resources