Android为多媒体文件生成缩略图

来源:互联网 发布:淘宝双十一直播视 编辑:程序博客网 时间:2024/05/22 12:34

1、Video

对于视频,取第一帧作为缩略图,也就是怎样从filePath得到一个Bitmap对象。

 

01privateBitmap createVideoThumbnail(String filePath) {
02        Bitmap bitmap =null;
03        MediaMetadataRetriever retriever =newMediaMetadataRetriever();
04        try{
05           retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
06            retriever.setDataSource(filePath);
07            bitmap = retriever.captureFrame();
08        }catch(IllegalArgumentException ex) {
09           // Assume this is a corrupt video file
10        }catch(RuntimeException ex) {
11           // Assume this is a corrupt video file.
12        }finally{
13            try{
14                retriever.release();
15            }catch(RuntimeException ex) {
16               // Ignore failures while cleaning up.
17            }
18        }
19        returnbitmap;
20    }
Android提供了MediaMetadataRetriever,由JNI(media_jni)实现。
看得出MediaMetadataRetriever主要有两个功能:MODE_GET_METADATA_ONLY和MODE_CAPTURE_FRAME_ONLY
这里设mode为MODE_CAPTURE_FRAME_ONLY,调用captureFrame取得一帧。

另外还有两个方法可以用:
extractMetadata 提取文件信息,ARTIST、DATE、YEAR、DURATION、RATING、FRAME_RATE、VIDEO_FORMAT
和extractAlbumArt 提取专辑信息,这个下面的音乐文件可以用到。

2、Music
对于音乐,取得AlbumImage作为缩略图,还是用MediaMetadataRetriever。

 

01privateBitmap createAlbumThumbnail(String filePath) {
02        Bitmap bitmap =null;
03        MediaMetadataRetriever retriever =newMediaMetadataRetriever();
04        try{
05            retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY);
06            retriever.setDataSource(filePath);
07            byte[] art = retriever.extractAlbumArt();
08            bitmap = BitmapFactory.decodeByteArray(art,0, art.length);
09        }catch(IllegalArgumentException ex) {
10        }catch(RuntimeException ex) {
11       }finally{
12           try{
13                retriever.release();
14            }catch(RuntimeException ex) {
15                // Ignore failures while cleaning up.
16           }
17        }
18        returnbitmap;
19    }
retriever.extractAlbumArt()得到的是byte数组,还需要一步用BitmapFactory编码得到Bitmap对象。

3、Image
图片就很简单了

 

1Bitmap bm = null;
2        Options op =newOptions();
3        op.inSampleSize = inSampleSize;
4        op.inJustDecodeBounds =false;
5        bm = BitmapFactory.decodeFile(mFile.getPath(), op);
能直接得到Bitmap对象,把图片缩小到合适大小就OK。
同样上面的Video和Music,retrive到Bitmap后也需要缩小处理。
原创粉丝点击