How to save file in Android to specific folder? - android

btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ivdisplayphoto.setDrawingCacheEnabled(true);
Bitmap bitmap = ivdisplayphoto.getDrawingCache();
String message = getIntent().getExtras().getString("");//== String message= "/folder1/folder2/"
String root = (Environment.getExternalStorageDirectory().getPath()+message);
// String root = (Environment.getExternalStorageDirectory().getPath()+""/folder1/folder2/");
text.setText(root);
final File newDir = new File(root + "//saved_imag");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "safed to your folder", Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
}
});
Hey I'm new to Android and I have been trying to make an app.
I am having trouble with part of saving the camera images into the newly created folder.
the problem is in to message variable i can create the file "newDir" if i use simple string "/folder1/folder2/",but if I use the "message" variable
  I cant create it

// Your problem with message variable. Below is working code please go through it.
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
}
});
//save you image when calling the onActivityResult method after capture image.
//When user click image vai camera then directly store to save_image folder.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image_" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

// But the problem it is I want to record the photo in the path rot=root+message
// In another activity I have a qr-code scanner, every qr-code scanned corresponds to a path the content of every qr-code pass of the first activity to the second, the content is stored in the variable "message".
//Then i am obliged to use the variable "message" so that I draw to change the path to store my photo.
String message = getIntent().getExtras().getString("");
String root=Environment.getExternalStorageDirectory().toString();
String rot = root+message;
// String root = (Environment.getExternalStorageDirectory().getPath()+""/folder1/folder2/");
final File newDir = new File(rot + "/dossier_photos");

Here you did simple mistake with Path :
Environment.getExternalStorageDirectory().getPath() = /storage/emulated/0
Environment.getExternalStorageDirectory().getPath()+message = /storage/emulated/0message
So you got error,
here path should be like below:
String root = (Environment.getExternalStorageDirectory().getPath()+"/"+message);

Related

How to programmatically set some images as invisible from the Gallery?

I need to make images invisible from my gallery and i see other answers on stackoverflow but did not work for me .
this how i done that programmatically .
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==REQUEST_CAMERA){
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
File file = new File(path);
Bitmap bmp = CommonMethod.compressImage(file, getContext());
Log.e(TAG, "onActivityResult --: "+ String.format("Size : %s", getReadableFileSize(file.length())));
mCustomerImage = CommonMethod.bitmapToByteArray(bmp);
imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
Log.e(TAG, "image: "+ imageTemplateStr );
//CommonMethod.SaveImage(bmp);
imageCustomer.setImageBitmap(bmp);
CommonMethod.SaveImage(bmp);
}
}else if(requestCode==SELECT_FILE){
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
File file = new File(path);
Bitmap bmp = CommonMethod.compressImage(file, getContext());
Log.e(TAG, "onActivityResult --: "+ String.format("Size : %s", getReadableFileSize(file.length())));
mCustomerImage = CommonMethod.bitmapToByteArray(bmp);
imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
//CommonMethod.SaveImage(bmp);
Log.e(TAG, "image: "+ imageTemplateStr );
imageCustomer.setImageBitmap(bmp);
CommonMethod.SaveImage(bmp);
}
}
SaveImage Method :
public static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/safco_private_pics");
if (!myDir.exists()) {
myDir.mkdirs();
}
File newFile = new File(root,".nomedia");
try {
FileWriter writer = new FileWriter(newFile);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
getPathFromURI method
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Now by that code images from gallery are not shown but images from Camera are visible in gallery and also .nomedia file not created.
Images are stored in my folder that i created and also in DCIM/Camera folder . I do not know why
What is wrong can anybody help me . ?
If you want to save the image for temporarily then you can use following code
File outputDir = context.getCacheDir(); // context should be the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);
Instead of
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/safco_private_pics");
For more details about cache dir read this: https://stackoverflow.com/a/6528104/7708305
But, If you want your file to be hidden and persisted on the permanent storage regardless of usage you can use following code.
File file = new File(root + "/.hidden_folder");
The dot(.) before the file/folder name makes it hidden.
let your image in hidden folder
//replace
File myDir = new File(root + "/safco_private_pics");
//with
File myDir = new File(root + "/.safco_private_pics");
put dot(.)before directory name it will create hidden directory and put your image in that directory

Image Saved In Phone Storage Instead of SD Card and Also not Showing in Phone Gallery Why?

I am having an application containing different images using ImageView and ViewPager. I want to save the current image shown through ImageView in SD Storage. But it always saved in Phone Storage successfully.
I want to save the image in SD Card and also saved image not showing in Gallery Why? Kindly help me out in this issue:
public void SaveIamge() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Cute_Baby_Images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
int currentImagePos = viewPager.getCurrentItem();
Drawable drawable = viewPager.getResources().getDrawable(images[currentImagePos]);
Bitmap finalBitmap = ((BitmapDrawable) drawable).getBitmap();
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, "Sucessfully Save Image", Toast.LENGTH_LONG).show();
}
Environment.getExternalDirectory() returns phone storage. To get location of SD card, check Find an external SD card location
To make the images appear in gallery, you should let the media scanner scan the file using MediaScannerConnection.scanFile()
Check Image, saved to sdcard, doesn't appear in Android's Gallery app
Create a function called getDirectory()
private static File getDirectory(String variableName, String... paths) {
String path = System.getenv(variableName);
if (!TextUtils.isEmpty(path)) {
if (path.contains(":")) {
for (String _path : path.split(":")) {
File file = new File(_path);
if (file.exists()) {
return file;
}
}
} else {
File file = new File(path);
if (file.exists()) {
return file;
}
}
}
if (paths != null && paths.length > 0) {
for (String _path : paths) {
File file = new File(_path);
if (file.exists()) {
return file;
}
}
}
//If any there is no SECONDARY STORAGE are detected return INTERENAL STORAGE
return Environment.getExternalStorageDirectory();
}
Change your code to
public void SaveIamge() {
String root = getDirectory("SECONDARY_STORAGE").getAbsolutePath();
File myDir = new File(root + "/Cute_Baby_Images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
int currentImagePos = viewPager.getCurrentItem();
Drawable drawable = viewPager.getResources().getDrawable(images[currentImagePos]);
Bitmap finalBitmap = ((BitmapDrawable) drawable).getBitmap();
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, "Sucessfully Save Image", Toast.LENGTH_LONG).show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + root)));
}
I have added a broadcast to notify the MediaScanner to re-scan the filesystem for new files. This will fix the problem of images are not showing in the gallery.

How can I open images that save in internal storage (cache folder in Android/data/%package%/cache) in android gallery

After image was download, I save it in an internal storage at
Android/data/%packagename%/cache directory. below is a code.
private class SaveImageToStorage extends AsyncTask<Void,Void,Void>
{
String picName;
Bitmap bitmap;
public SaveImageToStorage(String name, Bitmap bitmap)
{
this.picName = name;
this.bitmap = bitmap;
}
#Override
protected Void doInBackground(Void... params) {
if(bitmap != null && !picName.isEmpty()) {
File file = new File(feedImagesCacheDir.getPath(), extractImageNameFromUrl(picName));
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.WEBP, 80, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
And after all of this I just want to open the image in android gallery.
I try below code and it doesn't work.It show me Toast "can't find the image".
So I've tried remove "file://", then it open gallery with nothing but something like broken image icon.
private void openImageInGallery(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://"+getFeedImagesCacheDir().getPath() + "/" + imgName+".webp"), "image/*");
startActivity(intent);
}
I think that maybe I save it in cache folder, so its became private with only access to my app.
How can I fix this?
Thanks.Sorry for my bad ENG.
Cache Image are not view directly because is save like encrypted format so first you download that image and save into SD card. use below code.
String root = Environment.getExternalStorageDirectory().toString();
String wallpaperFilePath=Android/data/%packagename%/cache/imagename;
File cacheDir = GlobalClass.instance().getCacheFolder(this);
File cacheFile = new File(cacheDir, wallpaperFilePath);
InputStream fileInputStream = new FileInputStream(cacheFile);
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = scale;
bitmapOptions.inJustDecodeBounds = false;
Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
wallpaperBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
By using this line you can able to see saved images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
You can download images into DCIM (your gallery folder in sdCard).
Then use below to open gallery:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Hope this help!

how to send images from one activity to other (using file path)

In my app, I am loading images from url's in listview. And onclick of list item I want to show it on next activity. I can pass bitmap through intent,But considering the size restriction of data that can be send through intent I dont want to send this way.
Anybody knows the better way of passing image from one activity to other.
I have heard about storing image in file and sending filepath using intent But don't know how?Please tell me how can I do it?
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
imageview=(ImageView) view.findViewById(R.id.icon);
description=(TextView) view.findViewById(R.id.firstLine);
rating=(TextView) view.findViewById(R.id.text1);
noofDownloads=(TextView) view.findViewById(R.id.text2);
noofComments=(TextView) view.findViewById(R.id.text3);
imageId=(TextView) view.findViewById(R.id.imageIdText);
publishdate=(TextView) view.findViewById(R.id.thirdLine);
attribution=(TextView) view.findViewById(R.id.attributionText);
Intent intent = new Intent(PicturesList.this, PictureDetail.class);
String fileName=description.getText().toString();
fileclass=new FileClass();
fileclass.saveImage(bitmap,fileName);
Intent intent = new Intent(PicturesList.this, PictureDetail.class);
intent.putExtra("imagePath",fileclass.getPath());
intent.putExtra("Description",description.getText());
intent.putExtra("Rate",rating.getText());
intent.putExtra("Downloads",noofDownloads.getText());
intent.putExtra("Comments",noofComments.getText());
intent.putExtra("PublishTime",publishdate.getText());
startActivity(intent);
}
});
}
And I have save images from ListAdapter
in
getview()
{
String fileName=lolpic.getDescription().toString();
FileClass fileclass=new FileClass();
fileclass.saveImage(bitmap,fileName);
and FileClass.java
public class FileClass {
Picture pic;
File file;
public void saveImage(Bitmap myBitmap,String fileName) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pictures");
String fname = fileName+".png";
file = new File (myDir, fname);
if (file.exists ())
{
file.delete ();
}
try {
FileOutputStream out = new FileOutputStream(file);
//myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
out.write(byteArray);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath()
{
return file.getPath();
}
}
use this to store image in sdcard
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "MyImage.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and next get the image path from file.getpath()
and use
intent.putExtra("imagePath", file.getpath());
to send the image through intent and use
String image_path = getIntent().getStringExtra("imagePath");
Bitmap bitmap = BitmapFactory.decodeFile(image_path);
myimageview.setImageDrawable(bitmap);
in your receiving activity to display an image onto the imageview named myimageview
Based on comments, looks like it should be myimageview.setImageBitmap(bitmap) . Didn't test this. But give a try to this also if above doesn't work
sending Activity
final String root = Environment.getExternalStorageDirectory().getAbsolutePath();
pathToImage = root + "/my/image/path/image.png";
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("imagePath", pathToImage);
startActivity(intent);
And in you receiving activity:
String path = getIntent().getStringExtra("imagePath");
Drawable image = Drawable.createFromPath(path);
myImageView.setImageDrawable(image);

Captured image is not stored in the specific folder in android

I have created a program to capture the image and that is getting stored into sdcard/dcim/camera folder. Now I am trying to save the captured image in my own directory created in sdCard, say "/somedir".
I am able to make the directory programmatically but the image file is not getting stored in it.
Can anybody tell me where I am doing wrong here??
Here is the code....
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
Bitmap mybitmap1; //mybitmap1 contain image. So plz dont consider that I don't have image in mybitmap1;
if(!folder.exists())
{
success = folder.mkdir();
Log.i("Log", "folder created");
}
else
{
Log.i("Log", "Folder already present here!!");
}
String fname = date +".jpg";
file = new File( folder,fname);
if (file.exists ())
file.delete ();
capturedImageUri = Uri.fromFile(file);
FileOutputStream out;
byte[] byteArray = stream.toByteArray();
try {
out = new FileOutputStream(file);
mybitmap1.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), mybitmap1, file.getName(), file.getName());
//MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (Exception e) {
e.printStackTrace();
}
Refer the below code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == 1 ) {
final Uri selectedImage = data.getData();
try {
bitmap = Media.getBitmap(getContentResolver(),selectedImage);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ filename);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are settings the wrong file name for the file. Just use this method if you want to use time in the name of image file.
private Uri getImageUri() {
// Store image in dcim
String currentDateTimeString = getDateTime();
currentDateTimeString = removeChar(currentDateTimeString, '-');
currentDateTimeString = removeChar(currentDateTimeString, '_');
currentDateTimeString = removeChar(currentDateTimeString, ':');
currentDateTimeString = currentDateTimeString.trim();
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM", currentDateTimeString + ".jpg");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}
private final static String getDateTime() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("PST"));
return df.format(new Date());
}
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt(current++, cur);
}
return r.toString();
}
Hers is what you need to do:
instead of
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
do this
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/abc");
if(folder.exists()){
//save your file then
}
else{
folder.mkdirs();
//save your file then
}
Make sure you use the neccessary permissions in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Categories

Resources