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

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

  1. private Bitmap createVideoThumbnail(String filePath) {
  2.         Bitmap bitmap = null;
  3.         MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  4.         try {
  5.             retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
  6.             retriever.setDataSource(filePath);
  7.             bitmap = retriever.captureFrame();
  8.         } catch(IllegalArgumentException ex) {
  9.             // 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.         return bitmap;
  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

  1. private Bitmap createAlbumThumbnail(String filePath) {
  2.         Bitmap bitmap = null;
  3.         MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  4.         try {
  5.             retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY);
  6.             retriever.setDataSource(filePath);
  7.             byte[] art = retriever.extractAlbumArt();
  8.             bitmap = BitmapFactory.decodeByteArray(art, 0, art.length);
  9.         } 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.         return bitmap;
  19.     }
复制代码

retriever.extractAlbumArt()得到的是byte数组,还需要一步用BitmapFactory编码得到Bitmap对象。

3、Image
图片就很简单了

  1.         Bitmap bm = null;
  2.         Options op = new Options();
  3.         op.inSampleSize = inSampleSize;
  4.         op.inJustDecodeBounds = false;
  5.         bm = BitmapFactory.decodeFile(mFile.getPath(), op);
复制代码

能直接得到Bitmap对象,把图片缩小到合适大小就OK。
同样上面的Video和Music,retrive到Bitmap后也需要缩小处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值