【问题标题】:Uri vs File vs StringPath in androidandroid中的Uri vs File vs StringPath
【发布时间】:2016-04-06 15:50:53
【问题描述】:

最近我正在做应用程序处理在外部存储上保存图像和加载图像。我对UriFileStringPath 感到很困惑。

例如,从图库中加载图片时,它使用Uri

if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { //Browse Gallery is requested
    //Get the path for selected image in Gallery
    Uri selectedImage = data.getData();
    String[] filePathColumn = { MediaStore.Images.Media.DATA };

    //Access Gallery according to the path
    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();

    loadImage(picturePath);         //load picture according the path
    image_View.setImageBitmap(pic); //Show the selected picture
}

然后在解码图像时,它使用StringPath

private void loadImage(String picturePath) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(picturePath,options);
    int height_ = options.outHeight;
    int width_ = options.outWidth;
    float ratio = width_/height_;
    int width = 480;
    int height = 480;
    if(width_>height_){
        height = Math.round(width / ratio);
    }else{
        width = Math.round(width*ratio);
    }

    options.inSampleSize = calculateInSampleSize(options, width, height);
    options.inJustDecodeBounds = false;
    pic=BitmapFactory.decodeFile(picturePath,options);
}

然后当从文件中读取字节时,它使用File

File cacheDir = getBaseContext().getCacheDir();
//Form a directory with a file named "pic"
File f = new File(cacheDir, "pic");

try {
    //Prepare output stream that write byte to the directory
    FileOutputStream out = new FileOutputStream(f);
    //Save the picture to the directory
    pic.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

那么,有什么区别呢?只是用法不同但代表同一个目录吗?

【问题讨论】:

    标签: android


    【解决方案1】:

    内容 URI 类似于:

    content://media/external/images/media/53
    

    这里ContentResolver的作用是让你根据这个URI访问图片,你不需要知道文件的文件名或其他属性,你只需要这个URI就可以访问图片。

    字符串路径是存储的图像的物理地址,如下所示:

    file:///mnt/sdcard/myimage.jpg
    

    最后,File 是您需要对文件进行操作的最低级别的处理程序。它使用字符串路径作为参数来创建或打开文件以进行读/写。

    在您提供的示例中,进度如下:

    1-您要求ContentResolver根据提供的URI为您提供真实的文件路径

    2- 根据提供的路径将位图文件加载到pic 对象

    3- 您创建一个名为“pic”的文件并将pic 对象压缩为 JPG 并写入它

    【讨论】:

    • 感谢您的解释。你能帮我看看stackoverflow.com/questions/36466483/…
    • @SamTew 我在那里回答了你的问题
    • 我没有意识到回答它的人是你。非常感谢
    • @SamTew 请接受这两个答案,以便可以关闭问题
    猜你喜欢
    • 1970-01-01
    • 2016-01-05
    • 2013-09-06
    • 2015-02-22
    • 2022-10-13
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多