Android将图像保存在内部存储中

时间:2018-03-04 02:35:38

标签: android uri android-gallery

假设我创建了一个从图库或任何其他目录中选择图像的意图,我应该从onActivityResult()获取一个uri,是否可以将精确的uri复制到本地文件(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???


    }

1 个答案:

答案 0 :(得分:0)

使用此代码写入文件

忽略代码

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

<强>加了:

Bitmap获取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;

}

Bitmap保存到文件

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