Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Get thumbnail of image on SD card, given Uri of original image

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?

like image 483
Rahat Ahmed Avatar asked Feb 06 '11 21:02

Rahat Ahmed


3 Answers

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

like image 70
sujith s Avatar answered Oct 22 '22 16:10

sujith s


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.

like image 6
Gubbel Avatar answered Oct 22 '22 18:10

Gubbel


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);
}
like image 2
David Vávra Avatar answered Oct 22 '22 18:10

David Vávra