I have two text fields and a button to capture image,on click of camera button it will capture image but entered text in text fields will be refreshed,
i have a method which will clear text and images(from the SD card).I have called this method in onCreate method.I dont want to clear those text fields upto capturing image,how to handle this?
Here is my code to capture image:
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Device doesn't support capturing images!";
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// user is returning from capturing an image using the camera
if (requestCode == CAMERA_CAPTURE) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
DateFormat dateFormat = new SimpleDateFormat("HH-mm-ss");
Date date = new Date();
String imgcurTime = dateFormat.format(date);
File imageDirectory = new File(ImagePath);
if (!imageDirectory.exists()) {
imageDirectory.mkdirs();
}
String _path = ImagePath + imgcurTime + ".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
out.flush();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In low memory situations the android will kill the background activities. In your situation when camera activity started the background activity which starting the camera is may be destroying. And when you came back from camera it is recreated. So persist your edit text data same them in onSavedInstance() method and reassign them in the onRetoreInstance() method.
I hope this may works.
Related
I am trying to capture an image and save cropped image instead of original image with specified name.
At the moment I am able to crop and show on imageview but I need to know how to save cropped image instead of original, Here is the code.
final int CAMERA_CAPTURE = 1;
final int CROP_PIC = 2;
private Uri picUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn = (Button) findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
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();
performCrop();
}
// user is returning from cropping the image
else if (requestCode == CROP_PIC) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
/**
* this function does the crop operation.
*/
private void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
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", 2);
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, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
I am new to android and I really want to know how I can do this, any kind of help is much appriciated.
So the question is: How to save a bitmap
Sometimes saving bitmaps takes a long time. I suggest you to use AsyncTask in order to avoid annoying lags in your app.
public class saveFile extends AsyncTask<Void, Void, File>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);//Show user that app is working in backgrind
}
#Override
protected File doInBackground(Void... params) {
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/CropedImage";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
String format = new SimpleDateFormat("yyyyMMddHHmmss",
java.util.Locale.getDefault()).format(new Date());
File file = new File(dir, format + ".png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
thePic.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
return file;
}
#Override
protected void onPostExecute(File result) {
progressBar.setVisibility(View.INVISIBLE);
String respath=result.getPath().toString();
Toast.makeText(MainActivity.this, "Saved at "+respath, Toast.LENGTH_LONG).show();
MediaScannerConnection.scanFile(MainActivity.this, new String[] { result.getPath() }, new String[] { "image/jpeg" }, null);
}
}
And then call AsyncTask:
new saveFile().execute();
Android does not have any crop intent you can download crop libraries Click here
I'm working on an app which allows user to choose a picture from gallery and then I start a activity to crop it.
I want to send the cropped image back to calling activity.
Both activities extend AppCompatActivity.
Calling activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// start image crop activity
String dataString = data.getDataString();
Intent intent=new Intent(this, CropPhotoActivity.class);
intent.putExtra("SELECTED_PICTURE_FOR_CROP", dataString);
startActivityForResult(intent, CROP_PICTURE);
}
else if(requestCode == CROP_PICTURE) {
// get cropped bitmap
Bitmap bitmap = (Bitmap) data.getParcelableExtra("CROPPED_IMAGE");
profilePhoto.setImageBitmap(bitmap);
}
}
}
In the crop image activity, I have a button, which on click should return back to calling activity:
Button okButton = (Button)findViewById(R.id.ok_button);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE", cropped_bitmap);
setResult(RESULT_OK, returnIntent);
finish(); // sometimes restarts app
}
});
Sometimes the bitmap gets returned correctly whereas sometimes it does not and the app gets restarted without error. Why is this happening? Does putExtra have anything to do with bitmap size or anything else?
You could try substituting
AppcompatActivity.this.finish()
(where AppcompatActivity is your class name)
for:
finish(); // sometimes restarts app
Or, create a method in the calling Activity:
public static void cropComplete(Activity activity)
{
activity.startActivity(activity, AnotherActivity.class);
activity.finish();
}
Theres's a limit for data length passed as extra in a intent. Try not passing the dataString value; instead you should save the image as a temporary file, pass the path in the intent and then load the image from your calling activity (or you can just save the dataString in a static helper class).
In the crop activity (saving bitmap code from Save bitmap to location):
// Save bitmap
String filename = "tempImage.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
FileOutputStream out = null;
try {
out = new FileOutputStream(dest);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Get image file path
String path = dest.getAbsolutePath();
// Set result with image path
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE_PATH", path);
setResult(RESULT_OK, returnIntent);
finish();
In the caller activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CROP_PICTURE) {
// Get image file path
String imagePath = data.getStringExtra("CROPPED_IMAGE_PATH");
// Load image
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}
I'm completely news on android thing and unfortunately with little few time to learn it by the right way, I have a work to release.
The problem is: I need to take a picture and process her with an algorithm that I made.
I did it by the easiest way that I could find, I know it looks like really trahsie for those who really get android (sorry)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePic();
protected void takePic(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 100);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle extras = data.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
Algorithm(mImageBitmap)
But it doesn't process, it takes a photo, ask to save or cancell and leaves the application, I have already made by different ways (creating a new activity), but nothing seems to work
Heres how I did it
To go to the camera:
Somewhere, declaire a fileUri variable and hold onto it
Uri fileUri;
final int TAKE_PICTURE=100;//this can be any int, really
public void goToCamera(){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo;
try
{
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
Log.v(TAG, "Here(after createTempFile)");
photo.delete();
}
catch(Exception e)
{
Log.v(TAG, "Can't create file to take picture!" + e.getMessage());
Toast.makeText(context, "Please check SD card!", Toast.LENGTH_SHORT).show();
return;
}
fileUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}
Then to retreive the image
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK){
this.getContentResolver().notifyChange(uri, null);
ContentResolver cr = this.getContentResolver();
Bitmap bitmap;
try
{
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(uri.getPath().toString(), ops);
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Failed to load", e);
}
}
}
The create temp file mentioned above:
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
Log.i(TAG, tempDir.toString());
if(!tempDir.exists())
{
Log.i(TAG, "Dir doesnt exist");
tempDir.mkdirs();
}
return File.createTempFile(part, ext, tempDir);
}
I realize this isn't probably as simple as you were hoping for, but this approach seemed to be as flexible and compatible as possible. Let me know if I left anything else out
I have code to show capture image from camera device like this
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String file_name = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + file_name + ".jpg");
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
intent.putExtra("mImageCaptureUri", mImageCaptureUri);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
and set image bitmap from path , it works when I capture image from portrait view camera device , but when I capture image from landscape view camera its getting error , I think its because my activity to retrieve image is portrait . So can u give me advice in order to I can capture image from portrait or landscape view camera?? thanks
try this
at first start intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and then activity for result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if(data!=null && resultCode == RESULT_OK)
{
bitMapForProfilePic = (Bitmap) data.getExtras().get("data");
bitMapForProfilePic =Bitmap.createScaledBitmap(bitMapForProfilePic, getWindowManager().getDefaultDisplay().getWidth()/5, getWindowManager().getDefaultDisplay().getHeight()/4, true);
registration_profilePicID.setImageBitmap(bitMapForProfilePic); bitMapForProfilePic=null;
}
}
}
if u want to store the bitmap
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "profilepicture.PNG");
try {
outStream = new FileOutputStream(file);
bitMapForProfilePic.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then set the image
view.setImageBitmap(BitmapFactory.decodeFile("/sdcard/profilepicture.PNG"));
if u have any doubts let me know...
I've faced the similar problem in one of my apps, I've fixed it in the following way:
First save your instance state:
#Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString(IMAGE_FILE_PATH, imageFilePath); }
And then restore it:
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
ImageFilePath = state.getString(IMAGE_FILE_PATH); }
That works for me, but variable ImageFilePath should be global for your Activity so maybe there is more graceful way to achieve this
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using Camera and storing captured result in SDCard in android
I want to get picture from camera app, save it on SD and set imageView.
I made a code below. saving and imageView sometimes works. but sometimes the picture is saved on SD and imageView doesn't work.
When imageView doesn't work, it seems that mOutUri become null in onActivityResult.
I have tried to save a mOutUri on SharedPreferences in clkbutton. I can see the uri in onActivityResult but imageView doesn't work. at this time, mOutUri is also null.
public void clkbutton(View v){
Intent intent = new Intent();
// open camera app
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// save data in SD card
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String newPicFile = df.format(date) + ".jpg";
mNewPicFile = newPicFile;
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mOutUri = Uri.fromFile(outFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutUri);
startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageURI(mOutUri);
}
It's so weird that it sometimes errors and sometimes works.
In onActivityResult before you setImageUri you should check if file exists. You can lose mOutUri content when app changes orientation, and it happend sometime when you open camera. You should implement in activity onSaveInstanceState where you store into preferences your uri and onRestoreInstanceState where you restore your uri.
try the following code:
static Uri capturedImageUri=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(), (cal.getTimeInMillis()+".jpg"));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
capturedImageUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(i, CAMERA_RESULT);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
//Bitmap photo = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(photo);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap( getApplicationContext().getContentResolver(), capturedImageUri);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and also dont forget to add some permissions in android manifets file like:
`note: add permission WRITE_EXTERNAL_STORAGE in manifest file.`