0

i'm making an app in which there is a case in which i want to make a folder in gallery named "private folder" (when user clicks on the button "Create Folder") and then programmatic-ally want to insert a image in it say "mypic.png" ... can anyone help plzzz

AndDev
  • 41
  • 1
  • 9

1 Answers1

0

You can create directories in external memory like this:

File mydir = new File(Environment.getExternalStorageDirectory() + "/privatefolder/");
mydir.mkdirs();

then you can save your files in it in different ways. this is a one of them which you have already a filepath and you want to copy that image to your folder:

String oldFilePath = "Your old FilePath";
String newFilePath = new File(Environment.getExternalStorageDirectory() + "/privatefolder/" + "Your image name.jpg");

File newFile = copyFile(oldFilePath , newFilePath);

public static File copyFile(String from, String to) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            int end = from.toString().lastIndexOf("/");
            String str1 = from.toString().substring(0, end);
            String str2 = from.toString().substring(end+1, from.length());
            File source = new File(str1, str2);
            File destination = new File(to, str2);
            if (source.exists()) {
                FileChannel src = new FileInputStream(source).getChannel();
                FileChannel dst = new FileOutputStream(destination).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
            return destination;
        }

    } catch (Exception e) {
        return null;
    }
    return null;
}

also don't forget to add this permission in manifest:

< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Edit:

for saving from drawables to sdcard:

//first get a bitmap from your image. if your image name is "photo" do it like this
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.photo);

//then creat your directory. and then copy your image (in this code image format is PNG)
File mydir = new File(Environment.getExternalStorageDirectory() + "/privatefolder/");
mydir.mkdirs();
File file = new File(mydir, "photo.PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();

used some of this answer code.

Community
  • 1
  • 1
SaDeGH_F
  • 471
  • 1
  • 3
  • 14
  • thanks man i got half of my answer ... you told me a way to move a image from a source to destination but i want to insert an image from "drawables" to private folder e.g i want to move @/drawable/mypic.png .. can you tell plz – AndDev Sep 14 '14 at 09:22
  • @HassanAkhtar I Edited my code as you asked. hope it helps ;) – SaDeGH_F Sep 14 '14 at 13:32