获取视频的缩略图

在写IMDemo的过程中,需要将录制的小视频上传,需要上传视频的缩略图,分为两步就可以得到缩略图的路径

1.获取视频的bitmap

/**
 * 获取视频文件缩略图
 * @param videoPath 视频文件的路径  如:/storage/emulated/0/IM/video/1523343139288.mp4
 * @return Bitmap 返回获取的Bitmap
 */
public Bitmap getVideoThumbnail(String videoPath) {
    Bitmap bitmap = null;
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(videoPath);
        bitmap = retriever.getFrameAtTime();
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        ex.printStackTrace();
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        }
    }
    return bitmap;
}

2.将bitmap保存到本地

/**
 * Bitmap保存成File
 *
 * @param bitmap input bitmap
 * @return String output file's path
 */
public static String bitmap2File(Bitmap bitmap) {
    String name = "" + System.currentTimeMillis();

    File sampleDir = new File(Environment.getExternalStorageDirectory() + File.separator + "IM/video/");

    File f = new File(sampleDir, name + ".jpg");
    if (f.exists()) f.delete();
    FileOutputStream fOut = null;
    try {
        fOut = new FileOutputStream(f);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        fOut.flush();
        fOut.close();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return f.getAbsolutePath();
}

你可能感兴趣的:(Android)