How to create separate private folder for captured images? - android

I am trying to create a separate folder for captured images using the code and below code is working fine for creating separate folder and images also saved in that folder
My problem is captured images also appear in gallery and I don't want to show them in my gallery, Can someone help me please what will I do for my requirement
code:
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
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) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
File compressedFile1 = Utilities.saveImage(this, bitmap);
}
public static File saveImage(Context context, Bitmap imgBitmap) {
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;
}

It's appearing in Gallery because you are using getExternalStorageDirectory(), this returns a public path accessible by all apps. So one solution is to use a private external path context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), folderName), the files saved here will not be accessible by MediaScanner and therefore not visible in the Gallery, although they will be deleted when your app is deleted.

Related

How to create separate folder for captured images with losing quality

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());

Save image from camera without being resized

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;
}

How can I save output image from camera directly to file without compression?

After compressing the file and then texting it, it recompresses again and is very choppy
I use Intent to bring up the camera. I get the result and bring up Intent to send as text.
private void takePic() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File file = writebitmaptofilefirst("route_image",photo);
Uri uri = Uri.fromFile(file);
fileToDelete = file;
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("address", "8001111222");
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("image/jpg");
startActivityForResult(sendIntent,3);
}
else if (requestCode == 3){
if (fileToDelete.exists()) fileToDelete.delete();
}
}
public static File writebitmaptofilefirst(String filename, Bitmap source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
outStream = new FileOutputStream(file);
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
This works great except the resulting image texted is choppy. If I send the same pic that ends up in the Gallery it converts that down and the result is 100 times better at the receiving end. Can I save the Bitmap I get from the camera call directly without compression, the file will be deleted after the sending of the picture. The user actually takes the pic and then hits the send button on the default sms app.
To save an image directly without compressing use AndroidBmpUtil:
new AndroidBmpUtil().save(source, file);
Instead of
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
use
source.compress(Bitmap.CompressFormat.PNG, 100, outStream);
JPEG is a lossy format hence the choppy result.

How can i save the image taken from camera intent to be used as a profile image?

In my app the user can take an image from the camera and use as a profile picture. Everything works, except that when the user leaves the app and returns then the image isn't there anymore. So how can I save that image to stay there even when the user exits the app?
Code for camera intent:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
And onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
getLayoutInflater().inflate(R.layout.custon_header,null);
ImageView profimg = (ImageView) findViewById(R.id.roundedimg);
profimg.setImageBitmap(photo);
Could someone please assist me with this?
Thanks
data.getExtras().get("data");
only returns the thumbnail of the image which would be on low quality. You have to specify on your camera intent a location where the image will be saved:
File outputFile = new File(Environment.getExternalStorageDirectory() +"/myOutput.jpg");
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(Intent.EXTRA_OUTPUT,outputFile.getAbsolutePath());
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and on your activityResult, simply use the outputfile for your bitmap:
bitmap = BitmapFactory.decodeFile(outputFile.getAbsolutePath());
You can configure the intent to store the image, using EXTRA_OUTPUT like this:
Intent imageIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
File imageFolder = new File(Environment
.getExternalStorageDirectory(), "YourFolderName");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
File imageFile = new File(imagesFolder, "user.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
imageIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity.startActivityForResult(imageIntent, CAMERA_REQUEST);
So you have the path and can decode the file to bitmap.
You need to save that image in sd-card or phone memory so that it can be accessed when you open your app again. You are seeing that image as soon as you take the image because it is there in the memory and as soon as you leave the app, the memory is released.
private void SaveBitmapInDirectory(Bitmap bitmap, String fileName)
{
File direct = new File(Environment.getExternalStorageDirectory() + "/dirName");
if (!direct.exists())
{
File profilePic = new File("/sdcard/dirName/");
profilePic.mkdirs();
}
File file = new File(new File("/sdcard/dirName/"), fileName);
if (file.exists())
{
file.delete();
}
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
And load the file from directory in onCreate function by calling the following function:
void loadProfilerImage(String fileName)
{
File file = new File(new File("/sdcard/dirName/"), fileName);
if (file.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView.setImageBitmap(myBitmap);
}
}

How to create an app image folder to show in Android gallery

I have an app where the user creates an image and then I want to save it so it's visible form the default gallery application.
Now I don't want the pictures to be saved in the same folder as the pictures taken from the camera, I want them to be saved in a folder dedicated to the app, just like images from apps like whatsapp or facebook.
I've tried saving them in this two locations:
File imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+ File.separator + appDirectoryName + File.separator);
and here
File imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ File.separator + appDirectoryName + File.separator);
If I browse through the phone I see that I successfully save the images but they don't show in the gallery app. It is obvious that I'm missing something but I don't know what it is. Maybe adding some kind of metadata to the files or folders so the gallery recognizes them?
Well I found the answer in the end.
It turned out to be what I suspected. The saved image needs to have some metadata added in order to be seen in the gallery (at least in my device).
This is what I did:
OutputStream fOut = null;
File file = new File(imagePath,"GE_"+ System.currentTimeMillis() +".jpg");
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, this.getString(R.string.picture_title));
values.put(Images.Media.DESCRIPTION, this.getString(R.string.picture_description));
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis ());
values.put(Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
values.put("_data", file.getAbsolutePath());
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
I have had the same problem.
The second way is the correct way, but you don't see the images in the Gallery because the gallery needs to be refreshed.
So, you can wait a while until it refreshes itself, or you can use the MediaScanner -
look here
Hope this helped!
I did the following to get it to work:
public void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
String mCurrentPhotoPath = "file:" + image.getAbsolutePath(); // image is the created file image
File file = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
Try this
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(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 tried this it works perfectly.
private Uri imageUri;
String getimgname, getimgpath;
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "IMG"+System.currentTimeMillis()+".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
getimgname = photo.getName();
getimgpath = photo.getAbsolutePath();
Try this
MediaScannerConnection.scanFile(context,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});

Categories

Resources