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();
}
}
}
Related
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());
}
}
I use the following code to create image file and save them in to sd card
private File createImageFile(Bitmap bitmap) throws IOException {
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
PICNAME,
".png",
storageDir);
FileOutputStream out = null;
try {
out = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
The issue is that, though I take picture in full screen mode but the above code always saves the image in very less amount of dimension which is 320x240. why so.. is there by any means that I can save the image without resizing?
you can do it like this :
public static Uri takePhotoByCamera(Activity activity) {
File publicDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/myFolder");
double d = new Random().nextDouble();
File file = new File(publicDirectory, d + ".jpg");
String path = file.getAbsolutePath();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, path);
values.put(MediaStore.MediaColumns.TITLE, "New Picture");
values.put(MediaStore.Images.ImageColumns.DESCRIPTION, "From your Camera");
activity.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Uri photoUri = Uri.parse("file://" + path);
if (!publicDirectory.exists())
publicDirectory.mkdirs();
else if (!publicDirectory.isDirectory() && publicDirectory.canWrite()) {
publicDirectory.delete();
publicDirectory.mkdirs();
} else {
Log.d("tag550", "can't access");
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
activity.startActivityForResult(intent, requestCamera);
return photoUri;
}
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 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