public void uriToFilePath(Context context,Uri uri){
String filePath;
if (uri != null && "file".equals(uri.getScheme())) {
filePath = uri.getPath();
} else {
filePath = filenameFromUri(context,uri);
}
}
public String filenameFromUri(Context context, Uri uri) {
String filePath = getFilePathFromCursor(context, uri);
if (TextUtils.isEmpty(filePath)) {
filePath = getFilePathFromInputStream(context, uri);
}
return filePath;
}
@Nullable
private String getFilePathFromCursor(Context context, Uri uri) {
String filePath = null;
Cursor cursor = null;
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return filePath;
}
private String getFilePathFromInputStream(Context context, Uri uri) {
String filePath = "";
InputStream inputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, getBitMapOptions(context, uri));
inputStream.close();
filePath = saveImg(bitmap, FileUtil.getTempFileName());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return filePath;
}
public BitmapFactory.Options getBitMapOptions(Context context, Uri uri) throws Exception{
BitmapFactory.Options options= new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream stream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(stream, null, options);
stream.close();
int width = options.outWidth;
int height = options.outHeight;
if (width > height) {
int temp = width;
width = height;
height = temp;
}
int sampleRatio = Math.max(width / 900, height / 1600);
options = new BitmapFactory.Options();
options.inSampleSize = sampleRatio;
return options;
}
Android Content Uri to FilePath
猜你喜欢
转载自blog.csdn.net/huagbo/article/details/60956045
今日推荐
周排行