How can i catch picture that was taken? - android

I new in the android developing.
I want to develop simple application that will be able to take a picture using the cell phone camara and show it on the screen of the cell phone.
Is there some simple example that i can use ? or some code that can help me learn how to do it ?
Thanks for any help

to start camera you use
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
and here you have the handeling
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}

Try this.. Use the below code in onCreate
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
URI mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
Then OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
//Here you will get path of image stored in sdcard then pass it to next activity as your desires..
mImagePath = extras.getString("image-path");
mSaveUri = getImageUri(mImagePath);
Bitmap mBitmap = getBitmap(mImagePath);
// here mBitmap is assigned to any imageview and you can use it in for display
}
}
private Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
return BitmapFactory.decodeStream(in).copy(Config.ARGB_8888, true);
} catch (FileNotFoundException e) {
//Log.e(TAG, "file " + path + " not found");
}
return null;
}
}

Related

Android take and display photo from camera full resolution

I need to take a photo from my app and display it on an imageView, so now I´m using an intent request:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
bm = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bm);
}
}
}
The problem is that this code gets the thumbail of the image, not the image itself in full resollution, and I don´t know how to get it. I´ve searched and I have found this https://developer.android.com/training/camera/photobasics.html , but as I´m starting with this i don´t understand it.
Could somebody help me please?
Before you call CameraIntent create a file and uri based on that filepath as shown here.
filename = Environment.getExternalStorageDirectory().getPath() + "/test/testfile.jpg";
imageUri = Uri.fromFile(new File(filename));
// start default camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
imageUri);
startActivityForResult (cameraIntent, CAMERA_PIC_REQUEST);
Now, you have the filepath you can use it in onAcityvityResult method as following,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != CAMERA_PIC_REQUEST || filename == null)
return;
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageURI(imageUri);
Try out this code, It works for me.
Open camera using below code:
Intent intent = new Intent();
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+ ".your folder name"
+ File.separator + "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
capturedImageUri = Uri.fromFile(File.createTempFile("your folder name" + new SimpleDateFormat("ddMMyyHHmmss", Locale.US).format(new Date()), ".jpg", file));
intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(intent, Util.REQUEST_CAMERA);
} else {
Toast.show(getActivity(),"Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
In onActivityResult retrieve path of captured image:
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator
+ ".captured_Images"+ File.separator+ "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
selectedPath1 = capturedImageUri.toString().replace("file://", "");
Logg.e("selectedPath1", "OnactivityResult==>>" + selectedPath1);
imageLoader.displayImage(capturedImageUri.toString(), imgCarDetails1);
} else {
Toast.show(getActivity(), "Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
Add this permission in Manifest file:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
None of the answers worked for me, and I couldn´t use the tutorial as when creating the FileProvider, the xml gives me an error.
Finally I found this answer which works like a charm. Android Camera Intent: how to get full sized photo?

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 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);
}
}

How to properly write a photo into memory and get the URI (Honeycomb)?

I'm building an app that takes a photo and then e-mails it. For this I have to save it into the device's memory. The problem I'm getting is that while the app writes my file, it crashes at this particular line of code:
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(Environment.getExternalStorageDirectory()));
Lower you have the entire function and code:
private void takePicture(){
File outputFile = new File(Environment.getExternalStorageDirectory(), "image.jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(Environment.getExternalStorageDirectory()));
startActivityForResult(intent, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_PIC_REQUEST && resultCode == Activity.RESULT_OK){
picture = (Bitmap) data.getExtras().get("data");
pictureView.setImageBitmap(picture);
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "Picture");
values.put(Images.Media.BUCKET_ID, "picture_ID");
values.put(Images.Media.DESCRIPTION, "");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
pictureUri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try{
outstream = getContentResolver().openOutputStream(pictureUri);
picture.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
}catch(FileNotFoundException e){
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If I comment that line out, the app doesn't crash anymore. I need to get the photo's URI so I can then email it.
Any help from you guys more experienced out there would be greatly appreciated.
Try this
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File path = new File("/mnt/sdcard/YourDirectory");
path.mkdirs();
String fileName = "yourfile.jpg";
File file = new File(path, name);
camera.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(file));
startActivityForResult(camera, PICTURE_RESULT);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (PICTURE_RESULT == requestCode && Activity.RESULT_OK == resultCode) {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
////////// TASK TODO After result //////////
} else {
Toast.makeText(this, "sdcard not available", Toast.LENGTH_LONG).show();
}
}
}

Runtime Cropping an Image in android

I have already selected an image from SD card in my activity's ImageView using Intent.and now I want to show a fixed size moving Rectangle i.e. we have to use gesture and whatever portion of the image we want,then we are able to crop that.How can we do that?Its really tough for me to do?
Please help me in doing that?
Update-->I have been able to bring the rectangle and I m getting problem in cropping and saving that selected part.How to do this?
ok geetanjali. try this code this will open gallery and you can pick a photo to crop, it will store with name starts from apple, you can see cropped image in your activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop","true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 1);
}
private Uri getTempFile() {
if (isSDCARDMounted()) {
String f;
muri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"apple_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
//File f = new File(Environment.getExternalStorageDirectory(),"titus1.jpg");
try {
f=muri.getPath();
} catch (Exception e) {
}
return muri;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String filePath= muri.getPath();
Log.e("path", "filePath");
Toast.makeText(this, filePath, Toast.LENGTH_LONG).show();
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
image = (ImageView)findViewById(R.id.image);
image.setImageBitmap(selectedImage);
}
}
}

Categories

Resources