When I begin the camera intent I give it a file name I would like it to use. When I get this on the phone it uses the phones default file name. Which is no help as I need the image name later in the app.
Camera intent code...
public void onClick(View view) {
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
System.out.println(currentDateTimeString);
filename = ("/sdcard/" + currentDateTimeString + ".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), filename);
outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
filetype = "image/jpeg";
}
James,
Here is the function I use to capture an image and save it to a location of my choosing (sub folder with my app name).
public void imageFromCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d(TAG, "No SDCARD");
} else {
mImageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"MyApp",
"PIC"+System.currentTimeMillis()+".jpg");
mTempImagePath = mImageFile.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
startActivityForResult(intent, TAKE_PICTURE);
}
}
Related
Hi i am trying to create separate folder for captured images with out losing quality using below code but i am getting exception android.os.FileUriExposedException: file:///storage/emulated/0/myFolder/photo_20180504_102426.png exposed beyond app through ClipData.Item.getUri()
what did do mi-stack can some one correct my code
code:
String folder_main = "myFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory(), "/myFolder" + "/photo_" + timeStamp + ".png");
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, Constants.CAMERA_REQUEST_CODE);
private void onCaptureImageResult(Intent data) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
CircleImageView circleImageView = findViewById(formFields.get(imagePosition).getId());
circleImageView.setImageBitmap(thumbnail);
}
Put This on Your oncreate()
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
I am trying to open a camera intent and load the captured image in Android. The issue is that the camera app writes to the input URI correctly and the written data can be successfully decoded into a Bitmap only on the first call. On subsequent calls, it does not write any bytes to the input file and I checked that the file located at that URI still has 0 bytes after control returns from the camera app.
Here is the code for creating the file URI for input to camera app.
private #NonNull Uri getImageUri() {
Uri outputFileUri = null;
final String imageFileName = "JPEG_"
+ new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpeg" ;
File imagePath = new File(getFilesDir(), "images");
if(!imagePath.isDirectory()) {
imagePath.mkdirs();
}
File newFile = new File(imagePath, imageFileName);
if (newFile.exists()) {
newFile.delete();
}
try {
if(!newFile.createNewFile())
Log.e(MyActivity.class.getSimpleName(), "Error creating file");
} catch (IOException e) {
e.printStackTrace();
}
if(!(null != newFile && newFile.isFile())) {
throw new IllegalStateException("Cannot create file ");
}
outputFileUri = FileProvider.getUriForFile(
this.getApplicationContext(), "com.myapp.android.fileprovider", newFile);
if(null == outputFileUri){
throw new IllegalStateException( "Cannot create file for clicking image");
}
Log.e(MyActivity.class.getSimpleName(), "output file uri " + outputFileUri);
return outputFileUri;
}
Below is the code which opens the camera intent:
private List<Intent> getCameraIntents(#NonNull final Uri path){
if(!mCameraIntents.isEmpty()) return mCameraIntents;
#NonNull final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
#NonNull final List<ResolveInfo> listCam =
getPackageManager().queryIntentActivities(captureIntent, 0);
#NonNull final ArrayList<Intent> cameraIntents = new ArrayList<>(1);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, path);
cameraIntents.add(intent);
}
mCameraIntents.addAll(cameraIntents);
return cameraIntents;
}
/**
* Create a chooser intent to select the source to get image from.<br />
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br />
* All possible sources are added to the intent chooser.
*/
private Intent imageChooser() {
// Determine Uri of camera image to save.
#NonNull final Uri outputFileUri = getImageUri();
#NonNull final List<Intent> allIntents = getCameraIntents(outputFileUri);
allIntents.addAll(getGalleryIntents());
#NonNull final Intent mainIntent = allIntents.remove(allIntents.size() - 1);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(
mainIntent,
getResources().getString(R.string.snap_app_chooser_message));
// Add all other intents
chooserIntent.putExtra(
Intent.EXTRA_INITIAL_INTENTS,
allIntents.toArray(new Parcelable[allIntents.size()]));
mSnapUri = outputFileUri;
return chooserIntent;
}
Then I simply call this,
startActivityForResult(imageChooser(), REQUEST_IMAGE_CAPTURE);
Below is the code for decoding the captured image written in the file URI by the camera app.
#NonNull #Override protected Bitmap doInBackground(#NonNull final Uri... snapUris) {
Bitmap snap = null;
try {
Log.e(MyActivity.class.getSimpleName(), "snap uri " + snapUris[0]);
snap = MediaStore.Images.Media.getBitmap(
mActivity.get().getContentResolver(),
snapUris[0]);
if(null == snap ){
InputStream is =
mActivity.get().getContentResolver()
.openInputStream(snapUris[0]);
snap = BitmapFactory.decodeStream(is);
}
if (null == snap) {
Log.e(MyActivity.class.getSimpleName(), "Problem with uri path");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return snap;
}
}
Can anyone help me in understanding why the camera app is not writing the captured image into the file URI after the first call? What changes between the first time the camera intent in invoked and the next time it is invoked that it cannot write into the second and the subsequent file URIs. Is the outputstream of the camera app not properly closing after the first call?
I tested it on Xiaomi and Lenovo phones and am getting the same behavior.
Hi Guys My application quits just after the image is saved, I cannot see why, Please help?
This is the button pressed method, after the picture is taken I press save, The image gets saved where it needs to be saved but the application just quits after I press save, It does not say "Not Responding", it just quits
cam.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
leakerID = leakId.getText().toString();
String direc = "/e3softData/DCIM/";
String fileName = leakerID+".jpg";
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + direc);
// create this directory if not already created
dir.mkdir();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(dir, fileName);
String f = file.toString();
Uri uriSavedImage = Uri.fromFile(new File(f));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, 0);
}
});
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir = new File(Environment.getExternalStorageDirectory() + "/e3softData/DCIM/");
if (!dir.exists()) {
dir.mkdir();
}
String fileName = leakerID+".jpg";
output = new File(dir.getAbsolutePath(), fileName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, 0);
}
I just want to save a picture in my Imagefolder in my phone.
I have got 2 examples which I tried.
1. Example
My app crashes when I activate the onClick Method:
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1337);
}});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == 1337)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
else
{
Toast.makeText(AndroidCamera.this, "Picture NOt taken", Toast.LENGTH_LONG);
}
super.onActivityResult(requestCode, resultCode, data);
}
2. Example
Before I saved my taken Picture with Uri. But it saved my picture in a folder, which I can only access on my PC or with a FileApp. I don´t know how I can change the Path direction with Uri to my existing default image folder in my phone.
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
This is how I manage with saving images to specified imagefolder
When starting camera intent I define path and directory, where my image should be saved, and pass this as intetn extra when starting camera:
private void startCameraIntent() {
//create file path
final String photoStorePath = getProductPhotoDirectory().getAbsolutePath();
//create file uri
final Uri fileUri = getPhotoFileUri(photoStorePath);
//create camera intent
final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//put file ure to intetn - this will tell camera where to save file with image
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start activity
startActivityForResult(cameraIntent, REQUEST_CODE_PHOTO_FROM_CAMERA);
//start image scanne to add photo to gallery
addProductPhotoToGallery(fileUri);
}
And here are some of helper methods used in code above
private File getProductPhotoDirectory() {
//get directory where file should be stored
return new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),
"myPhotoDir");
}
private Uri getPhotoFileUri(final String photoStorePath) {
//timestamp used in file name
final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.US).format(new Date());
// file uri with timestamp
final Uri fileUri = Uri.fromFile(new java.io.File(photoStorePath
+ java.io.File.separator + "IMG_" + timestamp + ".jpg"));
return fileUri;
}
private void addProductPhotoToGallery(Uri photoUri) {
//create media scanner intetnt
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//set uri to scan
mediaScanIntent.setData(photoUri);
//start media scanner to discover new photo and display it in gallery
this.sendBroadcast(mediaScanIntent);
}
Hi
I'm looking for a way to save photos from the camera device directly without ask the user to save or not. I'm not implementing the Camera classes or overriding it. I'm simply using this code above. Do you have any ideas on how to do it?
TextReader tr = new TextReader(TextReader.DIRECTORY_EMPRESAS);
String path = TextReader.PARENT_PATH + "/" + TextReader.DIRECTORY_IMAGES;
String dataAtual = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
if(tr.verificaDiretorios(path)){
String pictureName = dataAtual + DADOS.get(0) + ".jpg";
File pathEmpresa = new File(path + "/" + TextReader.FILE_NAME);
File imageFile;
if(pathEmpresa.exists()){
imageFile = new File(pathEmpresa, pictureName);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
//startActivity(i);
startActivityForResult(i, 2);
}else{
if(pathEmpresa.mkdir()){
imageFile = new File(pathEmpresa, pictureName);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
//startActivity(i);
startActivityForResult(i, 2);
}else{
throw new IllegalStateException("Não foi possivel criar o diretorio: " + pathEmpresa);
}
}
You can't do that with an Intent. You need to use the Camera class.
Refer to the documentation:
http://developer.android.com/reference/android/hardware/Camera.html
Quick Example:
Camera camera = camera.open();
camera.takePicture(null, null, new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
Bitmap picture = BitmapFactory.decodeByteArray(data);
File f = new File(Environment.getExternalStorageDirectory(), "mydir");
f.mkdirs();//Grab file directory
f = new File(f, "mypicturefilename"); //Grab picture file location
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(f));
picture.compress(CompressFormat.JPEG, os);//Write image to file
picture.recycle(); //Clean up
}
}
});