So i've got a Uri of an image the user chooses out of images off his SD card. And i'd like to display a thumbnail of that image, because obviously, the image could be huge and take up the whole screen. Anyone know how?
You can simply create thumbnail video and image using ThumnailUtil class of java
Bitmap resized = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(file.getPath()), width, height);
public static Bitmap createVideoThumbnail (String filePath, int kind)
Added in API level 8 Create a video thumbnail for a video. May return null if the video is corrupt or the format is not supported.
Parameters filePath the path of video file kind could be MINI_KIND or MICRO_KIND
For more Source code of Thumbnail Util class
Developer.android.com
This code will do the job:
Bitmap getPreview(URI uri) {
File image = new File(uri);
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);
}
You may want to calculate the nearest power of 2 to use for inSampleSize
, because it's said to be faster.
I believe this code is fastest way to generate thumbnail from file on SD card:
public static Bitmap decodeFile(String file, int size) {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, o);
//Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = (int)Maths.pow(2, (double)(scale-1));
while (true) {
if (width_tmp / 2 < size || height_tmp / 2 < size) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(file, o2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With