假设我有一张存储在路径"/mnt/images/abc.jpg"
下的图片,我该如何获取系统生成的缩略图位图。我知道如何从Uri获取图像的缩略图,但不知道如何从文件路径获取。
假设我有一张存储在路径"/mnt/images/abc.jpg"
下的图片,我该如何获取系统生成的缩略图位图。我知道如何从Uri获取图像的缩略图,但不知道如何从文件路径获取。
你可以试试这个:
public static Bitmap getThumbnail(ContentResolver cr, String path) throws Exception {
Cursor ca = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
return MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MICRO_KIND, null );
}
ca.close();
return null;
}
您可以通过以下方式从文件中获取Uri
:
Uri uri = Uri.fromFile(new File("/mnt/images/abc.jpg"));
Bitmap thumbnail = getPreview(uri);
以下的函数可以为您提供缩略图:
Bitmap getPreview(Uri uri) {
File image = new File(uri.getPath());
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), Long.parseLong(_imageUri.getLastPathSegment()),type, null);
会是一个更好的选择,因为系统大部分时间会缓存缩略图。 - pankajagarwal作为其他人已经在他们的答案中提到的替代方法,但我发现获取缩略图的简单方法是使用ExifInterface
ExifInterface exif = new ExifInterface(pictureFile.getPath());
byte[] imageData=exif.getThumbnail();
if (imageData!=null) //it can not able to get the thumbnail for very small images , so better to check null
Bitmap thumbnail= BitmapFactory.decodeByteArray(imageData,0,imageData.length);
Bitmap resized = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(file.getPath()), width, height);
public static Bitmap createVideoThumbnail (String filePath, int kind)
API level 8引入 为视频创建一个缩略图。如果视频损坏或格式不受支持,则可能返回null。
参数 filePath 视频文件的路径 kind 可能是MINI_KIND或MICRO_KIND
public static Bitmap createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter)
使用示例:
Bitmap bitmap = BitmapFactory.decodeFile(img_path);
int origWidth = bitmap.getWidth();
int origHeight = bitmap.getHeight();
bitmap = Bitmap.createScaledBitmap(bitmap, origWidth / 10, origHeight / 10, false);
按照您的需求减小源文件。 在我的示例中,我将其减小了10倍。