以下代码适用于从图库中选择图片,否则我们无法获得缩略图,必须创建缩略图。
首先要找到MediaStore.Images.Media._ID。
public String[] getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
Cursor cursor = getActivity().getContentResolver().query(contentUri,
proj, null, null, null);
int path_index = cursor.getColumnIndexOrThrow(proj[0]);
int id_index = cursor.getColumnIndexOrThrow(proj[1]);
cursor.moveToFirst();
return new String[] { cursor.getString(path_index),
cursor.getLong(id_index) + "" };
}
从上面的getRealPathFromURI
现在我们有了MediaStore.Images.Media._ID
,使用这个id来查找缩略图。
public static Bitmap getThumbnail(ContentResolver contentResolver, long id) {
Cursor cursor = contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media.DATA},
MediaStore.Images.Media._ID + "=?",
new String[]{String.valueOf(id)},
null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
String filePath = cursor.getString(0);
cursor.close();
int rotation = 0;
try {
ExifInterface exifInterface = new ExifInterface(filePath);
int exifRotation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
if (exifRotation != ExifInterface.ORIENTATION_UNDEFINED) {
switch (exifRotation) {
case ExifInterface.ORIENTATION_ROTATE_180:
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotation = 90;
break;
}
}
} catch (IOException e) {
Log.e("getThumbnail", e.toString());
}
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
contentResolver, id,
MediaStore.Images.Thumbnails.MINI_KIND, null);
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
}
return bitmap;
} else
return null;
}
要使用上述LOC
已更新
String[] imageInfo = getRealPathFromURI(Uri.parse("YOUR_IMAGE_PATH"));
yourImageView.setImageBitmap(getThumbnail(getActivity()
.getContentResolver(), Long.parseLong(imageInfo[1])));
Uri.parse("YOUR_IMAGE_PATH")
是内容URI。
Uri.fromFile(new File(imageUrl))
- dieter_h/storage/emulated/0/DCIM/100MEDIA/IMAG0823.jpg
@dieter_h - MarcusSystem.out.println(Uri.fromFile(new File(imageUrl)));
的输出是file:///storage/emulated/0/DCIM/100MEDIA/IMAG0823.jpg
。 - Marcus