Android : force close where get picture image from camera landscape - android

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

Related

Refreshing EditText Fields on click of Camera button

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.

Android: Resolution issue while saving image into gallery

I've managed to programmatically take a photo from the camera, then display it on an imageview, and then after pressing a button, saving it on the Gallery.
It works, but the problem is that the saved photo are low resolution.. WHY?!
I took the photo with this code:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Then I save the photo on a var using :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
}
}
and then after displaying it on an imageview, I save it on the gallery with this function:
public void SavePicToGallery(Bitmap picToSave, File savePath){
String JPEG_FILE_PREFIX= "PIC";
String JPEG_FILE_SUFFIX= ".JPG";
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File filePath = null;
try {
filePath = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, savePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picToSave.compress(CompressFormat.JPEG, 100, out);
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Add the pic to Android Gallery
String mCurrentPhotoPath = filePath.getAbsolutePath();
MediaScannerConnection.scanFile(this,
new String[] { mCurrentPhotoPath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
I really can't figure out why it lose so much quality while saved..
Any help please ? Thanks..
The photo you are displaying in the ImageView is a thumbnail :
data.getExtras().get("data");
Are you calling the method :
public void SavePicToGallery(Bitmap picToSave, File savePath)
with the thumbnail ?
Here you have all the steps describe to do what you want :
http://developer.android.com/training/camera/photobasics.html
data.getExtras().get("data") only get thumbnail.
To do it properly, you have to declare global uri variable
Uri imageCapturedUri ;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
// mImageCaptureUri is your Uri
}
}

open an camera app by intent and save picture on the SD and imageView [duplicate]

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.`

Using phones camera , after capturing image activity doesn't return back to particular activity

I am capturing an image from my application using phone's camera and using android.provider.MediaStore.ACTION_IMAGE_CAPTURE.
After clicking capture button it shows save or discard. Clicking save button it returns back to camera not to application. and the image is saved in gallary not to the output file which i have declared.
Below is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent in=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(in, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK) {
Bitmap bm=(Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "player1.jpg");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
Intent pic=new Intent(pic1.this, GameMenu.class);
startActivity(pic);
finish();
}
}
else {
Toast.makeText(getApplicationContext(), "Canceled", Toast.LENGTH_LONG).show();
Intent pic=new Intent(pic1.this, Menu.class);
startActivity(pic);
finish();
}
Kindly suggest if any solution..
Thanks in advance...
EDIT 1: I have checked this code on samsung galaxy y duos (android 2.3.6) its not working properly. And checked same on galaxy pop(2.2.1) and HTC wildfire(2.3.5) its working perfect.
Use below intent to capture the image and getTempFile() is where you mention the storage path
Intent photoPickerIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat",Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent,TAKE_PICTURE);
getTempFile:
private Uri getTempFile() {
File root = new File(Environment.getExternalStorageDirectory(), "Directory");
if (!root.exists()) {
root.mkdirs();
}
File file;
file = new File(root,filename+".jpeg" );
muri = Uri.fromFile(file);
photopath=muri.getPath();
Log.e("getpath",muri.getPath());
return muri;
}
Read here for more threads
If this is your whole code you have omitted setContentView(); Could be the reason it is not returning.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// setContentView() here
Intent in=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(in, 0);
}
Is the onActivityResult() method called?
I got the same problem, I have restart my device and test my application it works fine now. It might be possible with different code implementation application not responding. Try to reboot your device and test and let me know its working or not
you should creat your file opening your camera. you give the file URI as extra to the camera intent:
/**
* Capturing Camera Image will lunch camera app request image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
this is how I creat the file :
/**
* Creating file uri to store image
*
*
* #return Uri
*/
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getTempOutputMediaFile());
}
/**
* returning File
*
*
* #return File
*/
private File getTempOutputMediaFile() {
File appDirectory = this.getFilesDir();
File mediaStorageDir = new File(APP_NAME,
YOUR_IMAGE_DIRECTORY_NAME);
Log.i("mediaStorageDir", mediaStorageDir.getAbsolutePath());
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.i(YOUR_IMAGE_DIRECTORY_NAME,
"Oops! Failed create "
+ YOUR_IMAGE_DIRECTORY_NAME
+ " directory");
return null;
}
}
// Create a media file name
UUID temporaryImageUuid = UUID.randomUUID();
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ temporaryImageUuid + "." + YOUR_EXTENSION);
return mediaFile;
}
hi check the following code.after capturing image use startPreview() to release.it works for me
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.autoFocus(null);
mCamera.takePicture(null, null, mPicture);
Log.e("in capture button","onclick of this button"+ mCamera);
mCamera.startPreview();
}
});

android camera implementation

I am going to implement camera feature for my android app.for this, I searched a lot on internet and found 2 way to implement camera feature
design your own camera class using
android.view.SurfaceHolder and
android.view.SurfaceView
but this approach does look good to me as in this i have to take care of many things which will make my code complex.
2. I can use intent to call device camera. now again in this , i have 2 option
i ) using MediaStore.EXTRA_OUTPUT and not using MediaStore.EXTRA_OUTPUT
if i dont use MediaStore.EXTRA_OUTPUT I get a thumbnail which is not my actual requirement. i need image larger than this so if I scale this thumbnail, i find low quality image.
if i use MediaStore.EXTRA_OUTPUT I dint get any image on some device like samsung as in
onActivityResult(int requestCode, int resultCode, Intent intent)
I find intent is null . after searching a lot on internet, i found that this is device specific issue. i have Samsung Galaxy with me. and on this i am facing this issue.
i dont want my code to be a device specific code. so can any one tell me how to make my code generic. for your analysis, i am using following code
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator)
if(!root.exists()){
root.mkdirs();
}
sdImageMainDirectory = new File(root, "myPicName");
startCameraActivity();
}
catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
Uri outputFileUri;
protected void startCameraActivity() {
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
if(intent != null)
StoreImage(this, Uri.parse(intent.toURI()),
sdImageMainDirectory);
} catch (Exception e) {
e.printStackTrace();
}
Intent i = new Intent(this,Home.class);
i.putExtra("url", outputFileUri);
startActivity(i);
finish();
}
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Please check this link: Capture image using Intent
This code works fine in all the Samsung devices I have used (like Galaxy S, Galaxy Tab, Galaxy Pro).

Categories

Resources