2016-04-06 27 views
1

最近,我正在做保存圖像和加載圖像在外部存儲的應用程序交易。我很困惑Uri,FileStringPathUri vs文件與Android中的StringPath

例如,從圖庫中加載圖像時,它使用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(); 
} 

那麼,有什麼區別?它只是用法不同而代表相同的目錄?

回答

2

內容URI看起來像:

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

ContentResolver這裏的作用是讓你在此基礎上URI圖像的訪問,你不需要知道文件名或其他屬性文件,你只需要這個URI來訪問圖像。

路徑字符串是存儲看起來像圖像的物理地址:

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

最後,文件是您需要的文件進行操作的最低處理器。它使用字符串路徑作爲參數來創建或打開文件進行讀取/寫入。

在你們所提供的例子是進步:

1-你問ContentResolver給你

2-您加載一個位圖文件到基於pic對象基於所提供的URI真正的文件路徑所提供的路徑

3-您創建一個名爲「PIC」文件和壓縮pic對象爲JPG和寫入

+0

感謝您的解釋。你可以幫我看看http://stackoverflow.com/questions/36466483/how-the-codes-work-for-loading-image-from-gallery-android – SamTew

+0

@SamTew我在那裏回答你的問題 – Pooya

+0

I沒有意識到回答它的人就是你。非常感謝 – SamTew