1
最近,我正在做保存圖像和加載圖像在外部存儲的應用程序交易。我很困惑Uri
,File
和StringPath
。Uri 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();
}
那麼,有什麼區別?它只是用法不同而代表相同的目錄?
感謝您的解釋。你可以幫我看看http://stackoverflow.com/questions/36466483/how-the-codes-work-for-loading-image-from-gallery-android – SamTew
@SamTew我在那裏回答你的問題 – Pooya
I沒有意識到回答它的人就是你。非常感謝 – SamTew