Create a video thumbnail for a video. - Android Media

Android examples for Media:Video

Description

Create a video thumbnail for a video.

Demo Code


//package com.java2s;

import android.content.Context;

import android.graphics.Bitmap;

import android.media.MediaMetadataRetriever;
import android.net.Uri;

public class Main {
    /**//from  w  w w . j  a  v a  2s.  co m
     * Create a video thumbnail for a video. May return null if the video is
     * corrupt or the format is not supported.
     *
     * @param context application context
     * @param uri     the uri of video file
     */
    public static Bitmap createVideoThumbnail(Context context, Uri uri,
            int size) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(context, uri);
            bitmap = retriever.getFrameAtTime(-1);
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }

        if (bitmap == null)
            return null;

        // Scale down the bitmap if it's too large.
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int min = Math.min(width, height);
        if (min > size) {
            float scale = ((float) size) / min;
            int w = Math.round(scale * width);
            int h = Math.round(scale * height);
            bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
        }
        return bitmap;
    }
}

Related Tutorials