最近,我正在处理保存图像和在外部存储上加载图像的应用程序。我对Uri
,File
和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();
}
那么,有什么区别?它的用法不同但代表同一个目录吗?
答案 0 :(得分:3)
内容URI类似于:
content://media/external/images/media/53
此处ContentResolver
的作用是让您根据此URI访问图像,您不需要知道文件的文件名或其他属性,只需要此URI即可访问图像。
String Path是存储的图像的物理地址,如下所示:
file:///mnt/sdcard/myimage.jpg
最后,File是您需要使用文件操作的最低处理程序。它使用String Path作为参数来创建或打开文件以进行读/写。
在您提供的示例中,这是进度:
1-您要求ContentResolver
根据提供的URI
2-您根据提供的路径
将位图文件加载到pic
对象
3-你创建了一个名为" pic"并将pic
对象压缩为JPG并写入