Saving/renaming taken photos on sd-card in Android - android

i've used code from link below,was very helpfull,thank you:
http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html
need help with some photo issues! takePhoto() starts MediaStore.ACTION_IMAGE_CAPTURE, getFile() creates "Image keeper" directory and then saves taken picture under "Image-SOMENUMBER.jpg" name!in onActivityResult() i'd like to show taken picture as ImageView and i'd like to rename picture to something user inputs in edittext or something!
have two questions:
1) why can't i get ImageView to show my picture in try{} part? what am i doing wrong? how can i get a path of saved image?
2) is there a way i can enable users to name photos the way they want?(something like "save as" or renaming on some button click ect.)
any idea is welcome!thank you!
here is the code:
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getFile(this)) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), "Image keeper" );
if(!path.exists()){
path.mkdir();
}
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
File file = new File(path,name);
return file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case TAKE_PHOTO_CODE:
final File file = getFile(this);
try {
Bitmap captureBmp;
captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(captureBmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}

couldn't solve renaming part of my problem but this piece of code did a job for me! i'm sure it can be done a bit fancier but it works! it involves taking picture, saving to sd card and getting path to it!
ImageView iv;
static File image;
Uri ImageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
}
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
image = getFile(this);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), "Image keeper" );
if(!path.exists()){
path.mkdir();
}
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
File fileimage = new File(path, name);
return fileimage;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case TAKE_PHOTO_CODE:
try {
Bitmap captureBmp;
captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(image) );
ImageUri = Uri.fromFile(image);
String pathToImage = ImageUri.getPath();
iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(captureBmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
iv.setAdjustViewBounds(true);
break;
}
}
}

Related

How to take and save picturte and get picture path via button?

Here, I want To take picture and save it on sd card and get path via button.
That the picture path can see into TextView.
how can i do it?
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView mImage;
Button camera;
Button path;
TextView tvPath;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImage = (ImageView) findViewById(R.id.camera_image);
path = (Button) findViewById(R.id.btnPath);
tvPath = (TextView) findViewById(R.id.tvPath);
//1
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(thumbnail);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sorry for English.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
Uri filePath = data.getData();
String fullFilePath = FilePath.getPath(this, filePath);
if (fullFilePath != null) {
String filename = fullFilePath.substring(fullFilePath.lastIndexOf("/") + 1);
tvFilename.setText(filename);
}
}

how can i store gallery image in application directory

i have got the image directly from the camera , gallery to the image view in my app its all working fine.
Now what I want is to save this image from Image View to the application directory and also access it when required.
//You Can try This
File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/yourDirectoryname");
myDir.mkdirs();
File file = new File(myDir, yourImagePath);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imgBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
public class EditProfile extends AppCompatActivity {
ImageView imageView;
EditText Name,Email,MobileNo;
public static int count = 0;
String loginid;
Bitmap bitmap;
private static final int CAMERA_REQUEST = 1888;
String picturePath;
static int i=0;
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
byte[] image = null;
Button button1;
static File out;
String path1;
ImageView imageView1;
Bitmap photo ;
byte[] b=null;
Button EditProfile;
String Username;
String name;
String email;
String Imgpath;
String Imgpath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
EditProfile=(Button)findViewById(R.id.edit_profile);
Imgpath=getSharedPreferences("Bytearray",0).getString("Bytearray",null);
Imgpath1=getSharedPreferences("uri",0).getString("uri",null);
imageView=(ImageView)findViewById(R.id.profile_photo);
EditProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available", Toast.LENGTH_LONG).show();
}
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
String path=out.getAbsolutePath();
getSharedPreferences("path",0).edit().putString("path",path).commit();
imageView.setImageBitmap(mBitmap);
}
else if (requestCode == 2) {
imageView.setImageURI(selectedImage);
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]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// imageView.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap image=BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
imageView.setImageBitmap(image);
}
}
}
Initiate the camera intent like this by creating a file of known path,and after the image capture Your image appears in that path:
Uri capturedImageUri;//global variable
private void initiateImageCapture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
capturedImageUri = Uri.fromFile(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile == null || capturedImageUri == null) {
Utils.showLongToast(getActivity(), "error");
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
startActivityForResult(takePictureIntent, Constants.INTENT_IMAGE_CAPTURE);
else
Utils.showLongToast(getActivity(), "try again);
}
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}

Android "TAKE PHOTO" - Image which is clicked is getting saved as a corrupt image

I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if(options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("Assert")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
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();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});

Save Image from drawable to sdcard in camera activity

I'm working on a project, that read image file from drawable folder through ImageView, it loaded successfully through
ImageView view = (ImageView) findViewById(R.id.imageView);
view.setOnTouchListener(this);
buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
now after pressing takePicture button , image should save in sdcard, it is taking snapshot but not saving the image with that, the code is below
File file = new File(mScreenshotPath + "/" + System.currentTimeMillis() + ".jpg");
FileOutputStream fos;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
Toast.makeText(AndroidCamera.this,
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
Please help me for this issue....Thanks in advance
You can save photos in Android without the need for an OutputStream and all the other logic that accompanies it. Here is a simple recipe which will do what I think you are trying to accomplish. Pay special attention to the Intent and how it is used to set up the saving of the image, as this is I think where you are going wrong.
public class PhotoActivity extends Activity implements OnClickListener {
private Button takePicture;
private String path;
private File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
takePicture = (Button) findViewById(R.id.button1);
takePicture.setOnClickListener(this);
path = Environment.getExternalStorageDirectory() + "/my_image.png";
imageFile = new File(path);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = Uri.fromFile(imageFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivity(i);
break;
}
}
}
private static final int CAMERA_REQUEST = 1888;
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
startActivityForResult(intent, CAMERA_REQUEST);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
photo = (Bitmap) data.getExtras().get("data");
}
}
private Uri getImageUri() {
File file1 = new File(Environment.getExternalStorageDirectory() + "/Camerafolder");
if (!file1.exists())
{
file1.mkdirs();
}
File file = new File(Environment.getExternalStorageDirectory() + "/Camerafolder/"+"img"+".png");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}

Camera activity returning null android

I am building an application where I want to capture an image by the default camera activity and return back to my activity and load that image in a ImageView. The problem is camera activity always returning null. In my onActivityResult(int requestCode, int resultCode, Intent data) method I am getting data as null. Here is my code:
public class CameraCapture extends Activity {
protected boolean _taken = true;
File sdImageMainDirectory;
Uri outputFileUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameracapturedimage);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
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();
}
}
protected void startCameraActivity() {
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
{
if(resultCode==Activity.RESULT_OK)
{
try{
ImageView imageView=(ImageView)findViewById(R.id.cameraImage);
imageView.setImageBitmap((Bitmap) data.getExtras().get("data"));
}
catch (Exception e) {
// TODO: handle exception
}
}
break;
}
default:
break;
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}
}
Am I doing anything wrong?
You are getting wrong because you are doing it wrong way.
If you pass the extra parameter MediaStore.EXTRA_OUTPUT with the camera intent then camera activity will write the captured image to that path and it will not return the bitmap in the onActivityResult method.
If you will check the path which you are passing then you will know that actually camera had write the captured file in that path.
For further information you can follow this, this and this
I am doing it another way. The data.getData() field is not guaranteed to return a Uri, so I am checking if it's null or not, if it is then the image is in extras. So the code would be -
if(data.getData()==null){
bitmap = (Bitmap)data.getExtras().get("data");
}else{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
I am using this code in the production application, and it's working.
I had a similar problem. I had commented out some lines in my manifest file which caused the thumbnail data to be returned as null.
You require the following to get this to work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
I hope this resolves your issue
If you phone is a Samsung, it could be related to this http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/
There is another open question which may give additional information
If you are using an ImageView to display the Bitmap returned by Camera Intent
you need to save the imageview reference inside onSaveInstanceState and also restore it later on inside onRestoreInstanceState. Check out the code for onSaveInstanceState and onRestoreInstanceState below.
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
String mCurrentPhotoPath;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageView = (ImageView) findViewById(R.id.imageView1);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void startCamera(View v) throws IOException {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
photoFile = createImageFile();
//intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
&& resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
System.out.println(imageBitmap);
imageView.setImageBitmap(imageBitmap);
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
System.out.println(mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
System.out.println(mCurrentPhotoPath);
imageView = (ImageView) findViewById(R.id.imageView1);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
System.out.println(mCurrentPhotoPath);
imageView = (ImageView) findViewById(R.id.imageView1);
}
}
after many search :
private static final int TAKE_PHOTO_REQUEST = 1;
private ImageView mImageView;
String mCurrentPhotoPath;
private File photoFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saisir_frais);
mImageView = (ImageView) findViewById(R.id.imageViewPhoto);
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST && resultCode == RESULT_OK) {
// set the dimensions of the image
int targetW =100;
int targetH = 100;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoFile.getAbsolutePath(), bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
// stream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath(),bmOptions);
mImageView.setImageBitmap(bitmap);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
photoFile = createImageFile();
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
} catch (IOException e) {
e.printStackTrace();
}
}
Try following code
{
final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (fullPath.contains("DCIM")) {
//get bitmap from fullpath here.
return;
}
}
while (imageCursor.moveToNext());
While taking from camera few mobiles would return null. The below workaround will solve. Make sure to check data is null:
private int CAMERA_NEW = 2;
private String imgPath;
private void takePhotoFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAMERA_NEW);
}
// to get the file path
private 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;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_NEW) {
try {
Log.i("Crash","CAMERA_NEW");
if(data!=null &&(Bitmap) data.getExtras().get("data")!=null){
bitmap = (Bitmap) data.getExtras().get("data");
personImage.setImageBitmap(bitmap);
Utils.saveImage(bitmap, getActivity());
}else{
File f= new File(imgPath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize= 4;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
personImage.setImageBitmap(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
You can generate bitmap from the file that you send to camera intent. Please use this code...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
{
if(resultCode==Activity.RESULT_OK)
{
int orientation = getOrientationFromExif(sdImageMainDirectory);// get orientation that image taken
BitmapFactory.Options options = new BitmapFactory.Options();
InputStream is = null;
Matrix m = new Matrix();
m.postRotate(orientation);//rotate image
is = new FileInputStream(sdImageMainDirectory);
options.inSampleSize = 4 //(original_image_size/4);
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
// set bitmap to image view
//bitmap.recycle();
}
break;
}
default:
break;
}
}
private int getOrientationFromExif(String imagePath) {
int orientation = -1;
try {
ExifInterface exif = new ExifInterface(imagePath);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_NORMAL:
orientation = 0;
break;
default:
break;
}
} catch (IOException e) {
//Log.e(LOG_TAG, "Unable to get image exif orientation", e);
}
return orientation;
}
File cameraFile = null;
public void openChooser() {
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,new Intent[]{takePhotoIntent});
startActivityForResult(chooserIntent, SELECT_PHOTO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
if (selectedImage != null) {
//from gallery
} else if (cameraFile != null) {
//from camera
Uri cameraPictureUri = Uri.fromFile(cameraFile);
}
}
break;
}
}
Try this tutorial. It works for me and use permission as usual in manifesto & also
check permission
https://androidkennel.org/android-camera-access-tutorial/
After a lot of vigorous research I finally reached to a conclusion.
For doing this, you should save the image captured to the external storage.
And then,retrieve while uploading.
This way the image res doesnt degrade and you dont get NullPointerException too!
I have used timestamp to name the file so we get a unique filename everytime.
private void fileChooser2() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName=getPictureName();
fi=pictureName;
File imageFile=new File(pictureDirectory,pictureName);
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
startActivityForResult(intent,PICK_IMAGE_REQUEST2);
}
Function to create a file name :
private String getPictureName() {
SimpleDateFormat adf=new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = adf.format(new Date());
return "The New image"+timestamp+".jpg";//give a unique string so that the imagename cant be overlapped with other apps'image formats
}
and the onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PICK_IMAGE_REQUEST2 && resultCode==RESULT_OK )//&& data!=null && data.getData()!=null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
File picDir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile=new File(picDir.getAbsoluteFile(),fi);
filePath=Uri.fromFile(imageFile);
try {
}catch (Exception e)
{
e.printStackTrace();
}
StorageReference riversRef = storageReference.child(mAuth.getCurrentUser().getUid()+"/2");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
Edit: give permissions for camera and to write and read from storage in your manifest.

Categories

Resources