I am trying to deleted camera captured images using below code but images are not deleting i have tried lot but still no result can some one help me please
code:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, Constants.CAMERA_REQUEST_CODE);
private void onCaptureImageResult(Intent data) {
File file = saveImage(this, data);
if(file !=null){
file .getCanonicalFile().delete();
}
}
public File saveImage(Context context, Intent data) {
File mediaFile = null;
try {
Bitmap imgBitmap = (Bitmap) data.getExtras().get("data");
File sd = Environment.getExternalStorageDirectory();
File imageFolder = new File(sd.getAbsolutePath() + File.separator +
"FOSImages");
if (!imageFolder.isDirectory()) {
imageFolder.mkdirs();
}
mediaFile = new File(imageFolder + File.separator + "fos_" +
System.currentTimeMillis() + ".jpg");
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
imgBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
fileOutputStream.close();
return mediaFile;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return mediaFile;
}
try this :
File file = saveImage(this, data);
file.delete();
if(file.exists()){
file.getCanonicalFile().delete();
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
Related
I need to create the CAT_IMG folder in the root directory and retrieve it in list view. But the CAT_IMG folder is not creating in the root directory.I added permission in the manifest file. Please help me create a folder in root directory.
private void createDirectoryAndSaveFile(Bitmap imageToSave) {
File direct = new File(getApplicationContext().getFilesDir() + "/CAT_IMG");
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String fileName = "fav" + timeStamp + ".JPG";
if (!direct.exists()) {
File wallpaperDirectory = new File("/CAT_IMG");
wallpaperDirectory.mkdir();
}
File file = new File(new File("/CAT_IMG"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
createDirectoryAndSaveFile(photo);
Log.e("URI", data.getExtras().get("data") + "");
}
}
Code to retrieve it in list view:
private void getImages() {
String[] filenames = new String[0];
File path = new File(getApplicationContext().getFilesDir() + "/CAT_IMG");// add here your folder name
if (path.exists()) {
filenames = path.list();
}
for (int i = 0; i < filenames.length; i++) {
photos.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", photos.get(i));
Name.add(filenames[i]);
//Sno.add(i); }
}
}
i created a folder in root directory done small changes in my above code
`
private void createDirectoryAndSaveFile(Bitmap imageToSave) {
File direct = new File(getFilesDir() + "/CAT_IMG/");
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String fileName = "fav" + timeStamp + ".JPG";
if (!direct.exists()) {
// File wallpaperDirectory = new File("/CAT_IMG");
direct.mkdir();
}
File file = new File(direct, fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
createDirectoryAndSaveFile(photo);
Log.e("URI", data.getExtras().get("data") + "");
}
}`
My code for clicking on an image is:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 300);
Code of Activity Result:
if (requestCode == 300) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(number.equalsIgnoreCase("1"))
{
imageViewOneNumber.setImageBitmap(thumbnail);
image1="";
image1= getEncoded64ImageStringFromBitmap(thumbnail);
}
else
{
RelativeLayoutImage2.setVisibility(View.GONE);
FrameImage2.setVisibility(View.VISIBLE);
imageViewTwoNumber.setImageBitmap(thumbnail);
image2="";
image2= getEncoded64ImageStringFromBitmap(thumbnail);
}
}
Image of camera capture demo:
Please help me solve this problem. When I click on the photo from the camera it decreases the size of the image.
From the docs
The Android Camera application saves a full-size photo if you give it
a file to save into. You must provide a fully qualified file name
where the camera app should save the photo.
Sample Code from there
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
String mCurrentPhotoPath;
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;
}
Implement it like that:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File image = createImage(this);
Uri uri = Uri.parse("file://" + image.getAbsolutePath());
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_REQUEST);
public File createImage(Context context) throws IOException {
File dir = new File(Environment.getExternalStorageDirectory() + "/" + context.getString(R.string.company_name) + "/Images");
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new IOException("Something wrong happened at" + dir);
}
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss", Locale.getDefault()).format(new Date());
String imageName = context.getString(R.string.app_name) + "_" + timeStamp + ".jpg";
return new File(dir.getPath() + File.separator + imageName);
}
And finally in onActivityResult() you can get your image:
if (requestCode == CAMERA_REQUEST) {
//Here you can load image by Uri
}
Use this code may be its helps you
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String path=Environment.getExternalStorageDirectory()+File.separator+Constants.APP_FOLDER_NAME+File.separator+Constants.ATTACHMENTS_FOLDER_NAME;
File mediapath=new File(path);
if(!mediapath.exists())
{
mediapath.mkdirs();
}
captured_image_uri=null;
captured_image_uri=Uri.fromFile(new File(mediapath.getPath(),"Image"+System.currentTimeMillis()+".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT,captured_image_uri);
startActivityForResult(intent, Constants.PICK_FILE_FROM_CAMERA);
onActivityResult write this code
if(requestCode==Constants.PICK_FILE_FROM_CAMERA&&resultCode==getActivity().RESULT_OK)
{
try
{
if(captured_image_uri!=null) {
ExifInterface exifInterface = new ExifInterface(captured_image_uri.getPath());
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90: {
matrix.postRotate(90);
break;
}
case ExifInterface.ORIENTATION_ROTATE_180: {
matrix.postRotate(180);
break;
}
case ExifInterface.ORIENTATION_ROTATE_270: {
matrix.postRotate(270);
break;
}
}
FileInputStream fis = new FileInputStream(captured_image_uri.getPath());
Bitmap bmp = BitmapFactory.decodeStream(fis);
Bitmap rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
FileOutputStream fos = new FileOutputStream(captured_image_uri.getPath());
rotated.compress(Bitmap.CompressFormat.JPEG, 85, fos);
uploadFileToServer(captured_image_uri.getPath());
}
}catch (Exception e)
{
e.printStackTrace();
}
}
I need to save the pictures taken with my app in an specific folder. I've read many solutions to this problem but I couldn't make any of them work so I ask for help.
MainActivity.java
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Folder is already created
String dirName = Environment.getExternalStorageDirectory().getPath()
+ "/MyAppFolder/MyApp" + n + ".png";
Uri uriSavedImage = Uri.fromFile(new File(dirName));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
n++;
}
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Go through the following code , its working fine for me.
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File("/sdcard/DirName/", fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have used mdDroid's code like this:
public void startCamera() {
// Create photo
newPhoto = new Photo();
newPhoto.setName(App.getPhotoName());
//Create folder !exist
String folderPath = Environment.getExternalStorageDirectory() + "/PestControl";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdirs();
}
//create a new file
newFile = new File(folderPath, newPhoto.getName());
if (newFile != null) {
// save image here
Uri relativePath = Uri.fromFile(newFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, relativePath);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
Use Like this. It will work for you.
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//file path of captured image
filePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(filePath);
filename= f.getName();
Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
cursor.close();
//Convert file path into bitmap image using below line.
// yourSelectedImage = BitmapFactory.decodeFile(filePath);
Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
//put bitmapimage in your imageview
//yourimgView.setImageBitmap(yourSelectedImage);
Savefile(filename,filePath);
}
}
}
public void Savefile(String name, String path) {
File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/");
File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/"+n+".png");
if(!direct.exists()) {
direct.mkdir();
}
if (!file.exists()) {
try {
file.createNewFile();
FileChannel src = new FileInputStream(path).getChannel();
FileChannel dst = new FileOutputStream(file).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this will help you. for reference to use camera intent.
Here You Go. I tried the above solution they save the image to gallery but the image is not visible , a 404 error is visible on the image , and i figured it out .
public void addToFav(String dirName, Bitmap bitmap) {
String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
dirName + System.currentTimeMillis() + ".jpg";
Log.e("resultpath",resultPath);
new File(resultPath).getParentFile().mkdir();
if (Build.VERSION.SDK_INT < 29){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Photo");
values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put("_data", resultPath);
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream fileOutputStream = new FileOutputStream(resultPath);
bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
if(fileOutputStream != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}else {
OutputStream fos = null;
File file = new File(resultPath);
final String relativeLocation = Environment.DIRECTORY_PICTURES;
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation+"/"+dirName);
contentValues.put(MediaStore.MediaColumns.TITLE, "Photo");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis ());
contentValues.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
contentValues.put(MediaStore.MediaColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
contentValues.put(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
final ContentResolver resolver = getContentResolver();
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri uri = resolver.insert(contentUri, contentValues);
try {
fos = resolver.openOutputStream(uri);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fos != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
}
}
I have found an easier code to do it.
This is the code for creating the image folder:
private File createImageFile(){
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/App Folder/";
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "AppName_" + timeStamp;
String file = dir +imageFileName+ ".jpg" ;
File imageFile = new File(file);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = imageFile.getAbsolutePath();
return imageFile;
}
,And this is the code for launching the camera app and take the photo:
public void lunchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = createImageFile();
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.ziad.sayit",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Useful link for different ways of doing it: https://www.programcreek.com/java-api-examples/?class=android.os.Environment&method=getExternalStoragePublicDirectory
I am building an android app that accesses the camera but i am wanting to save the image into a specific folder but i have no idea how to go about it. do i use a URI builder?
this is the code i have to get the image from the camera.
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment
.DIRECTORY_PICTURES), "pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
You can create a file from your own directory like this:
private File openFileFromMyDirectory() {
File imageDirectory = null;
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
imageDirectory = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "com.myapp.camera");
if (!imageDirectory.exists() && !imageDirectory.mkdirs()) {
imageDirectory = null;
} else {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
return new File(imageDirectory.getPath() +
File.separator + "IMG_" +
dateFormat.format(new Date()) + ".jpg");
}
}
return null;
}
Then get bitmap from uri:
Bitmap mCameraBitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Finally save the bitmap into the file
private void saveImageToFile(File file) {
if (mCameraBitmap != null) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
if (!mCameraBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)) {
Toast.makeText(this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Saved image to: " + file.getPath(),
Toast.LENGTH_LONG).show();
}
outStream.close();
} catch (Exception e) {
Toast.makeText(this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
}
}
}
I have a fragment that takes a canvas drawing and saves it to external memory. I go into the device by connecting the USB and searching the file directory. I find it under Android/data/appname/files/img/nameofimage.png. Now I have a 2nd fragment that is saving pictures when the camera takes them but I can't find them.
Camera
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check that request code matches ours:
if (requestCode == CALL_BACK) {
// Check if your application folder exists in the external storage,
// if not create it:
File imageStorageFolder = new File(
Environment.getExternalStorageDirectory() + File.separator
+ "Camera");
if (!imageStorageFolder.exists()) {
imageStorageFolder.mkdirs();
Log.d("FILE",
"Folder created at: " + imageStorageFolder.toString());
}
// Check if data in not null and extract the Bitmap:
if (data != null) {
String filename = "image";
String fileNameExtension = ".jpg";
File sdCard = Environment.getExternalStorageDirectory();
String imageStorageFolderName = File.separator + "Camera"
+ File.separator;
File destinationFile = new File(sdCard, imageStorageFolderName
+ filename + fileNameExtension);
Log.d("FILE", "the destination for image file is: "
+ destinationFile);
if (data.getExtras() != null) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(
destinationFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("FILE", "ERROR:" + e.toString());
}
}
}
}
}
Canvas
capSig.setView(sign = new Sign(this.getActivity(), null))
.setMessage(R.string.store_question)
.setPositiveButton(R.string.save,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
sign.setDrawingCacheEnabled(true);
sign.getDrawingCache()
.compress(
Bitmap.CompressFormat.PNG,
10,
new FileOutputStream(
new File(
getActivity()
.getExternalFilesDir(
"img"),
"signature.png")));
} catch (Exception e) {
Log.e("Error ", e.toString());
}
onClick
private class ClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, CALL_BACK);
}
}
I don't fully understand the code, why is this saving to a different location. Also what would I need to do to get it to save under Android/data/appname/files/Camera/ ?
edit
the logcat tells me its being saved here: 06-08 16:21:49.333: D/FILE(4818): the destination for image file is: /storage/emulated/0/Camera/image.jpg Which I assume is listed as private in the files and that's why I cant find it. This does not tell me why its being saved here though.
2nd Edit
Current Code
private class ClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/Camera" ;
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
String FileName = "image";
File file = new File(path, FileName + ".jpg");
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CALL_BACK);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check that request code matches ours:
if (requestCode == CALL_BACK) {
Log.v("RESULT", "Picture Taken");
}
}
Try this code
private void TakePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/Camera" ;
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
String FileName = "image";
File file = new File(path, FileName + ".jpg");
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Remember
You need this Permission in your Manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />