Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android save image uri in internal storage [duplicate]

lets say I created an intent to pick an image from gallery or any other directory, I should get a uri from onActivityResult(), is it possible to copy the exact uri to a local file (intetnal storage).

    onActivityResult(){

     //get image uri
      Uri uri=data.getData();

      //create a file 

      File image_file=new File(path);


      //now how to save uri to image_File???


    }
like image 331
Hasan Bou Taam Avatar asked Oct 28 '25 05:10

Hasan Bou Taam


1 Answers

Use this code to write in file

Ignore below code

File path = context.getFilesDir();
File file = new File(path, "myfile.txt");
FileOutputStream stream = new FileOutputStream(file);

Uri uri = ....
String uriStr = uri.toString();
try {
  stream.write(uriStr.getBytes());
} finally {
  stream.close();
}

Reference

Added:

get Bitmap from Uri:

   public  Bitmap getContactBitmapFromURI(Context context, Uri uri) {
    try {

        InputStream input = context.getContentResolver().openInputStream(uri);
        if (input == null) {
            return null;
        }
        return BitmapFactory.decodeStream(input);
    }
    catch (FileNotFoundException e)
    {

    }
    return null;

}

Save Bitmap to file

    public  File saveBitmapIntoSDCardImage(Context context, Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(Util.getTempFileReceivedPath(conetext));
    myDir.mkdirs();

    String fname = "file_name" + ".jpg";
    File file = new File (myDir, fname);

    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return file;
}
like image 83
Abu Yousuf Avatar answered Oct 30 '25 15:10

Abu Yousuf