Search code examples
javaandroidvideomultimedia

Retrieve a thumbnail of a video


I'm trying to make an application for showing the best movie trailers. I'd like to show a grid view with the thumbnails of each video and then clicking them open a new Activity for playing the video.

Given a moment of the video, how can I retrieve the thumbnail? If that is complicated the first frame is enought too. Thanks


Solution

  • If you are using API 2.0 or newer this will work.

    To get video id:

    String[] proj = {
        MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DISPLAY_NAME,
        MediaStore.Video.Media.DATA
    };
    
    Cursor cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, 
                                        proj, MediaStore.Video.Media.DISPLAY_NAME+"=?",new String[] {"name.mp4"}, null);
    cursor.moveToFirst()
    id = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
    

    To get the thumbnail of the video:

    ImageView iv = (ImageView ) convertView.findViewById(R.id.imagePreview);
    ContentResolver crThumb = getContentResolver();
    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inSampleSize = 1;
    Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, id, MediaStore.Video.Thumbnails.MICRO_KIND, options);
    iv.setImageBitmap(curThumb);
    

    EDIT:

    If you are on android-8 (Froyo) or above, you can use ThumbnailUtils.createVideoThumbnail from video path:

    Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
        MediaStore.Images.Thumbnails.MINI_KIND);
    

    Hope it helps!