I am using Camera Function to Capture Images 2 times from different buttons. After Captured Image, It goes to Crop Option where user can crop the Image. It is also working fine.
But, now issue is that when user capture second image then App redirects to Crop image and show first image only rather than second capture image. I am also deleting image after It has been set to ImageView. Don't know what is the wrong ?
Please Help me to solve this issue.
My Code :
Bitmap bm_PhotoProof = null;
Bitmap bm_AddressProof = null;
private static final String TEMP_PHOTO_FILE = "tmp_ihis.jpg";
private static final int REQ_CODE_PICK_IMAGE_PHOTOPROOF = 0;
private static final int REQ_CODE_PICK_IMAGE_ADDRESSPROOF = 1;
imgPhotoProof.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
cameraIntent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(cameraIntent,
REQ_CODE_PICK_IMAGE_PHOTOPROOF);
}
});
imgAddressProof.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
cameraIntent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(cameraIntent,
REQ_CODE_PICK_IMAGE_ADDRESSPROOF);
}
});
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
File f = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
Log.e("getTempFile()->", e.getMessage().toString());
}
return f;
}
public void cropCapturedImage(Uri picUri, String Type) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 0);
cropIntent.putExtra("aspectY", 0);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
if (Type.equals("Photo")) {
startActivityForResult(cropIntent, 5);
} else {
startActivityForResult(cropIntent, 6);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQ_CODE_PICK_IMAGE_PHOTOPROOF) {
File tempFile = getTempFile();
cropCapturedImage(Uri.fromFile(tempFile), "Photo");
} else if (requestCode == REQ_CODE_PICK_IMAGE_ADDRESSPROOF) {
File tempFile = getTempFile();
cropCapturedImage(Uri.fromFile(tempFile), "Address");
}
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == 5) {
if (data != null) {
Bundle extras = data.getExtras();
bm_PhotoProof = extras.getParcelable("data");
}
imgPhotoProof_Pic.setImageBitmap(bm_PhotoProof);
File tempFile = getTempFile();
if (tempFile.exists()) {
tempFile.delete();
}
}
if (requestCode == 6) {
if (data != null) {
Bundle extras = data.getExtras();
bm_AddressProof = extras.getParcelable("data");
}
imgAddressProof_Pic.setImageBitmap(bm_AddressProof);
File tempFile = getTempFile();
if (tempFile.exists()) {
tempFile.delete();
}
}
}
}
}
I have solved this issue.Before, i was deleting just file. Now, I have also cleared cached and it solved my problem.
File tempFile = getTempFile();
if (tempFile.exists()) {
tempFile.delete();
}
to
File tempFile = getTempFile();
File cacheDir = getActivity().getCacheDir();
File file = new File(cacheDir, getTempFile().toString());
file.delete();
Related
I have a picture I want to post as imageButton but before posting it I have a cropper:
private void CropImage() {
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(uri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 180);
CropIntent.putExtra("outputY", 180);
CropIntent.putExtra("aspectX", 3);
CropIntent.putExtra("aspectY", 4);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent , 1);
}
catch (ActivityNotFoundException ex){
}
}
And when I select a picture from gallery or take a picture with my camera it shows a toast Editing is not supported for this Image, and I'm not sure what's really causing this.
This is my GalleryOpen() and CameraOpen():
private void GalleryOpen() {
GalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(GalleryIntent, "Select Images From Gallery"), 2);
}
private void CameraOpen() {
CamIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory(),
"file"+String.valueOf(System.currentTimeMillis())+ ".jpg");
uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", file);
CamIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
CamIntent.putExtra("return-data", true);
CamIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(CamIntent, 0);
}
And my OnActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK)
CropImage();
else if(requestCode == 2) {
if (data != null) {
uri = data.getData();
CropImage();
}
}
else if(requestCode == 1) {
if(data != null){
Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
imageHolder.setImageBitmap(bitmap);
}
}
}
I followed this to use camera from web-view..with upload,,,
So in that I am getting Default camera.. and I am capturing.. and Uploading...
So I want to Crop them...and Upload.. with Max 2 Megapixel resolution not more than 2Mp...
I followed this to use Crop...
I it Possible to use both intents together in web-view... and resolution should be low..
I mean after capture it should show crop... option... and then upload,,,
Can any one suggest me...
private void pickImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(Create_event.this);
builder.setTitle("Choose Image");
builder.setMessage("Select Image");
builder.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent photoPickerIntent = new Intent(
Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
dialog.dismiss();
}
});
builder.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
dialog.dismiss();
}
});
builder.show();
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 2 || requestCode == 1) {
try {
Intent cropIntent = new Intent(
"com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(data.getData(), "image/*");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
cropIntent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in
// onActivityResult
startActivityForResult(cropIntent, 3);
} catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
} else if (requestCode == 3) {
try {
Log.e("testing", "return data is " + data.getData());
String filePath = Environment.getExternalStorageDirectory()
+ "/" + TEMP_PHOTO_FILE;
System.out.println("path " + filePath);
uImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
uImage.compress(Bitmap.CompressFormat.PNG, 100, bao);
ba = bao.toByteArray();
ivcreateeventflyer.setImageBitmap(uImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
private File getTempFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}
Use this code to take pic from camera or gallery with crop functionality. hope it may be help you
So.. I'm trying to choose a picture using both camera and gallery, then pass it to an external library to crop image.
The problem lies with saving image after taking it with the camera. I've managed to get the camera running and take an image with it, then it display the image and the default Android Ok and back button. The Ok button responds to touch (as touch effect can be seen) but it doesn't do anything.
Here's the code for getting the file ready to save
date = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyyyyHHmmss");
dateString = simpleDateFormat.format(date);
dateBuilder = new StringBuilder().append(dateString).append(".jpg");
SAMPLE_CROPPED_IMAGE_NAME = dateBuilder.toString();
final String cameraDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/SamplePics/";
newDir = new File(cameraDir);
newDir.mkdirs();
This is the code for camera function
RelativeLayout.OnClickListener photoCameraWrapperHandler = new RelativeLayout.OnClickListener(){
#Override
public void onClick(View v) {
//Intent intent = new Intent(SignupStepThreeActivity.this, SignupStepFourActivity.class);
//startActivity(intent);
String cameraFile = SAMPLE_CROPPED_IMAGE_NAME;
newFile = new File(cameraFile);
try {
newFile.createNewFile();
}
catch (IOException e)
{
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
};
And here's the onActivityResult :
private static final int CAMERA_REQUEST = 1888;
private static final int REQUEST_SELECT_PICTURE = 0x01;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SELECT_PICTURE || requestCode == CAMERA_REQUEST) {
final Uri selectedUri = data.getData();
if (selectedUri != null) {
startCropActivity(data.getData());
} else {
Toast.makeText(SignupStepThreeActivity.this, R.string.toast_cannot_retrieve_selected_image, Toast.LENGTH_SHORT).show();
}
} else if (requestCode == UCrop.REQUEST_CROP) {
handleCropResult(data);
}
}
if (resultCode == UCrop.RESULT_ERROR) {
handleCropError(data);
}
}
Several updates before, it crashes when I click on camera button, I suspected it was because of I kind of take the uri of the image from storage but I haven't created the folder. Now I finally managed to get the camera running but not saving. The create folder part works tho..
public String getCamerPath(Context context) {
SharedPreferences prefs = context.getSharedPreferences("setCamerPath", 0);
String value = prefs.getString("getCamerPath", "");
return value;
}
public void setCamerPath(Context context, String value)
{
SharedPreferences prefs = context.getSharedPreferences("setCamerPath", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("getCamerPath", value);
editor.commit();
}
Uri outputFileUri = Uri.fromFile(newFile);
setCamerPath(this, outputFileUri.getPath());
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SELECT_PICTURE || requestCode == CAMERA_REQUEST) {
startCropActivity(getCamerPath(this));
} else if (requestCode == UCrop.REQUEST_CROP) {
handleCropResult(data);
}
}
if (resultCode == UCrop.RESULT_ERROR) {
handleCropError(data);
}
}
In the camera OnClickListener, I commented some stuffs like this :
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Uri outputFileUri = Uri.fromFile(newFile);
//cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
//setCamerPath(SignupStepThreeActivity.this, outputFileUri.getPath());
startActivityForResult(cameraIntent, CAMERA_REQUEST);
In my onActivityResult, I've modified a part of CAMERA_REQUEST :
else if (requestCode == CAMERA_REQUEST) {
Uri capturedImageUri = data.getData();
Bitmap bitmap;
if (capturedImageUri != null) {
startCropActivity(capturedImageUri);
} else {
Toast.makeText(SignupStepThreeActivity.this, R.string.toast_cannot_retrieve_selected_image, Toast.LENGTH_SHORT).show();
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
Uri imageUri = getImageUri(SignupStepThreeActivity.this, bitmap);
startCropActivity(imageUri);
}
}
So basically as I've been reading around for the past 4 hours, data is Intent. It will always be not null BUT will not always contain Uri itself for the image. Because I need the Uri for a library I'm using, I use a method called getImageUri from another Stackoverflow answer.
public static 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);
return Uri.parse(path);
}
Now the problem lies with bitmap image quality after taking the image, I'm going to tinker around with it and be back with an update.
This can also resolve the problem
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("camera", "onSaveInstance");
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d("camera", "onRestoreInstance");
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
I am passing image url to the following method
private void performCrop(Uri imageUri){
try {
Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setType("image/*");
intent.setDataAndType(imageUri, "image/*");
List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size >= 0) {
intent.setData(imageUri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("scale", true);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra("return-data", true);
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
System.out.println("before startActivityForResult");
try{
startActivityForResult(i, 2);
}catch(Exception e){
e.printStackTrace();
}
}
}
catch(ActivityNotFoundException anfe){
String errorMessage = "Whoops - your device doesn't support the crop action!";
//Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
//toast.show();
}
}
some of images are cropped but some image are not. When I crop image then my app's activity is closed and application starts it's previous or launcher activity so what is the problem??
the main issue is I am not getting any warning or error in log cat, and when I debug it the the till "System.out.println("before startActivityForResult");" the program excutes, that means it does not goes in or calling onActivityResult().
here is onActivityResult method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==2 && resultCode == getActivity().RESULT_OK){
System.out.println("inside logic...");
try{
if (data != null) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap bmp = extras.getParcelable("data");
imageView.setImageBitmap(bmp);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
this code works successfully for me.try it
private static final int CAMERA_REQUEST = 1;
public static final int MEDIA_TYPE_IMAGE = 1;
final int PIC_CROP = 12;
Button btnCamera;
ImageView iv;
Uri picUri;
static File mediaFile, sendFile;
btnCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onImgProfile();
}
});
void onImgProfile() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
picUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(captureIntent, CAMERA_REQUEST);
}
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#SuppressWarnings("unchecked")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
// if (Build.VERSION.SDK_INT < 19) {
try {
if (mediaFile.exists()) {
performCrop();
// new SavePhotoData().execute();
}
} catch (Exception e) {
// TODO: handle exception
}
// }
} else if (requestCode == 11) {
try {
picUri = data.getData();
Log.i("uri", "" + picUri);
performCrop();
} catch (Exception e) {
// TODO: handle exception
}
} else if (requestCode == PIC_CROP) {
// get the returned data
try {
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
// retrieve a reference to the ImageView
// display the returned cropped image
iv.setImageBitmap(thePic);
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
sendFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
FileOutputStream fOut = new FileOutputStream(sendFile);
thePic.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (resultCode == 3) {
Bundle b = data.getExtras();
b.getString("msg");
}
};
private void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
} catch (Exception e) {
// TODO: handle exception
}
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
this code works for not only kitkat but all cersion of android
Android all devices does not have a cropping intent according #CommonsWare http://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html
so better is to use libraries
some of them are:
https://github.com/jdamcd/android-crop
https://github.com/IsseiAoki/SimpleCropView
https://android-arsenal.com/details/1/3054
frnds,on clicking on button i open camera for taking picture ,i take picture successfull and now only two option is coming after clicking pic,"save" and "Discard",there is not any option for attaching the camera clicked image so how to attach image and display image in next view?
my code is ...
public void function2(int id){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST||requestCode == SELECT_PICTURE) {
try{
try{
selectedImageUri = data.getData();
//OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
//DEBUG PURPOSE - you can delete this if you want
if(selectedImagePath!=null){
Intent i=new Intent(MainMenu.this,Imageprview.class);
startActivity(i);
System.out.println(selectedImagePath);
}
else
System.out.println("selectedImagePath is null");
if(filemanagerstring!=null)
System.out.println(filemanagerstring);
else System.out.println("filemanagerstring is null");
//NOW WE HAVE OUR WANTED STRING
if(selectedImagePath!=null)
System.out.println("selectedImagePath is the right one for you!");
else
System.out.println("filemanagerstring is the right one for you!");
}catch (NullPointerException e) {
// TODO: handle exception
} }catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
} }
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else return null;
}
Button btnCam=(Button)findViewById(R.id.camBtn);
btnCam.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
//startActivity(detailActivity);
saveImage();
} });
}
public void saveImage()
{
try {
FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpeg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90);
startActivityForResult(intent,IMAGE_CAPTURE);
//startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE);
}
catch(IOException e) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK){
finish();
//imageView=(ImageView)findViewById(R.id.imageView1);
//imageView.setImageURI(imageUri);
Intent detActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
startActivity(detActivity);
//Log.d("ANDRO_CAMERA","Picture taken!!!");
//
}
}
}
IN DETAIL PROFILE ACTIVITY
public class detailProfile extends Activity{
String fname=new File(getFilesDir(),"MyFile.jpeg").getAbsolutePath();
//USING THIS FILE PATH YOU CAN LOAD THE IMAGE IN THIS ACTIVITY
}
YOU HAVE ANOTHER OPTION YOU CAN PASS THE IMAGE TO THROUGH THE INTENT AT THE TIME OF CREATING THE NEW INTENT AND AFTER THAT YOU CAN ACCESS THAT IMAGE THROUGH THE BUNDLE OBJECT IN THE NEW INTENT.
bytes[] imgs = ... // your image
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("img", imgs);
startActivity(intent)
in detailprofile
bytes[] receiver = getIntent().getExtra("imgs");
//using Byte array you can display your image in ur imageview
There is no such option available.you can save file in to sdcard or any external storage
c the code i have done for saving image in external storage.
public void onClick(View v)
{
if(v == imgForPhotograph) {
path = Environment.getExternalStorageDirectory() + "/photo1.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.gc();
if (requestCode == CAPTURE_IMAGE_ACTIVITY) {
if (resultCode == Activity.RESULT_OK) {
try {
// Call function MakeFolder to create folder structure if
// its not created
if(imageBitmap != null) {
imageBitmap = null;
imageBitmap.recycle();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
imageBitmap = BitmapFactory.decodeFile(path, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm
byte[] bmpbyte = baos.toByteArray();
//
Imagebase64= Base64.encodeToString(bmpbyte, Base64.DEFAULT); // set
imgForPhotograph.setImageBitmap(imageBitmap);
isImageTaken = true;
// Name for image
IMAGEPATH = getString(R.string.Image)
+ System.currentTimeMillis();
SaveImageFile(imageBitmap,IMAGEPATH);
} catch (Exception e) {
Toast.makeText(this, "Picture Not taken",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
All The Best....
Hi guys, this code is working. For camera and stored into sd card:
public class CampicsaveActivity extends Activity
{
/** Called when the activity is first created. */
FrameLayout frm;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
frm=(FrameLayout)findViewById(R.id.preview);
Button btnCam=(Button)findViewById(R.id.buttonClick);
btnCam.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
// startActivity(detailActivity);
saveImage(0);
} });
}
public void saveImage(int IMAGE_CAPTURE)
{
try
{
FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpeg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90);
startActivityForResult(intent,IMAGE_CAPTURE);
//startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE);
}
catch(IOException e)
{;}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
finish();
//imageView=(ImageView)findViewById(R.id.imageView1);
//imageView.setImageURI(imageUri);
Intent detActivity = new Intent(getBaseContext(),CampicsaveActivity.class);
startActivity(detActivity);
//Log.d("ANDRO_CAMERA","Picture taken!!!");
//
}
}
}
}
}